MFC编程实例:从零实现MVC框架之增删改查(4)
小职 2018-07-05 来源 : 阅读 1169 评论 0

摘要:本文主要向大家介绍了MFC编程实例:从零实现MVC框架之增删改查(4),通过具体的内容向大家展示,希望对大家学习MFC编程实例有所帮助。

本文主要向大家介绍了MFC编程实例:从零实现MVC框架之增删改查(4),通过具体的内容向大家展示,希望对大家学习MFC编程实例有所帮助。

概述

这一章节貌似有点小复杂。为了实现对象的增删改查,我们需要做点功课

1:生成id,我们采用手动生成id的方法,这里我们特意也为id创建了一个池子,所有的id都从池子里面取。

2:对象状态: 新建状态、持久状态、查询状态。查询状态是内部处理。

      处于新建状态下的对象可以进行保存操作,不能更新和删除
      处于持久状态下的对象可以进行更新和删除操作,不能保存。

3:执行器:我们所有的sql的执行都要靠执行器执行并返回结构。

4:数据装配:处理sql中的占位符以及返回结果的处理。

5:事务:提交和回滚。我们这里只是提供了这个方法,但是还没有具体实现。因为我们现在的连接都是自动提交的不涉及到事务问题。等到后面章节我们做AOP事务管理的时候会具体实现。


实现思路

为了简单起见,我们把增删改查方法都定义到实体类上。通过继承AbstractEntity可以继承这些方法。不过具体实体类不用实现这些方法。每个实体类在进行每次增删该查方法时,都会重新获取一个执行器,然后通过执行器执行sql。执行器也在AbstractEntity中创建。下面看具体代码:

 

实体类:

接口

[java] view plain copy

1. package com.hc.core;  

2.   

3. import java.sql.SQLException;  

4.   

5. /** 

6.  * 实体接口 所有数据库实体都必须实现这个接口 

7.  * @author chuer 

8.  * @date 2014-7-16 下午12:07:47 

9.  * @version V1.0 

10.  */  

11. public interface IEntity {  

12.   

13.     public long getId();//获得实体主键  

14.   

15.     public void setId(long id);//设置实体主键  

16.   

17.     public void persist() throws SQLException;//增  

18.   

19.     public void remove() throws SQLException;//删  

20.   

21.     public IEntity get(long id) throws SQLException;//查  

22.       

23.     public void update(String columnName) throws SQLException;//改  

24.       

25.     public void setExecute();//设置执行器  

26.       

27.       

28.     public void rollBack();  

29.       

30.       

31.       

32.       

33. }  


抽象实现

[java] view plain copy

1. package com.hc.core;  

2.   

3. import java.sql.SQLException;  

4.   

5. /** 

6.  * 抽象实体类 

7.  * @author chuer 

8.  * @date 2014-7-16 下午12:08:42 

9.  * @version V1.0 

10.  */  

11. public abstract class AbstractEntity implements IEntity {  

12.   

13.     protected AbstractExecute<AbstractEntity> execute;  

14.     protected EntityStatus status;  

15.   

16.     public AbstractEntity(){  

17.         this.status = EntityStatus.NEW;//状态为新建  

18.     }  

19.       

20.     @Override  

21.     public void persist() throws SQLException {  

22.         //持久化对象 只有新建的对象才可以进行持久化  

23.         if(this.status == EntityStatus.NEW){  

24.             setExecute();  

25.             try{  

26.                 execute.save(this);  

27.             }catch(SQLException e){  

28.                 rollBack();  

29.                 throw e;  

30.             }  

31.             this.status = EntityStatus.PERSIST;  

32.         }  

33.     }  

34.       

35.       

36.     @Override  

37.     public void remove() throws SQLException{  

38.         //删除用户  只有持久化的对象才可以进行删除操作  

39.         if(this.status == EntityStatus.PERSIST){  

40.             setExecute();  

41.             try {  

42.                 execute.delete(this);  

43.             } catch (SQLException e) {  

44.                 rollBack();  

45.                 throw e;  

46.             }  

47.             this.status = EntityStatus.NEW;  

48.         }  

49.     }  

50.   

51.     @Override  

52.     public  AbstractEntity get(long id) throws SQLException {  

53.         this.setId(id);  

54.         this.status = EntityStatus.QUERY;  

55.         setExecute();  

56.         execute.get(this);  

57.         this.status = EntityStatus.PERSIST;  

58.         return this;  

59.     }  

60.       

61.     @Override  

62.     public void update(String columnName) throws SQLException{  

63.         //只有持久化对象才能进行更新操作  

64.         if(this.status == EntityStatus.PERSIST){  

65.             setExecute();  

66.             try{  

67.                 execute.update(this, columnName);  

68.             }catch(SQLException e){  

69.                 rollBack();  

70.                 throw e;  

71.             }  

72.         }  

73.     }  

74.   

75.     public EntityStatus getStatus() {  

76.         return status;  

77.     }  

78.   

79.     public void setStatus(EntityStatus status) {  

80.         this.status = status;  

81.     }  

82.   

83.     @Override  

84.     public void setExecute() {  

85.         execute = ExecuteFactory.getExecute();  

86.     }  

87.   

88.     @Override  

89.     public void rollBack() {  

90.     }  

91.       

92.       

93.       

94.       

95.       

96. }  

具体实现

[java] view plain copy

1. package com.hc.sample.entity;  

2.   

3. import java.sql.SQLException;  

4.   

5. import com.hc.annotation.Column;  

6. import com.hc.annotation.Entity;  

7. import com.hc.core.AbstractEntity;  

8. /** 

9.  *  

10.  * @author chuer 

11.  * @date 2014-7-16 上午9:33:02 

12.  * @version V1.0 

13.  */  

14. @Entity(entityName="UserEntity",tableName="user_m")  

15. public class UserEntity  extends AbstractEntity{  

16.       

17.     public UserEntity(){  

18.         super();  

19.     }  

20.       

21.     @Column(type=long.class,name="id",isPrimary=true)  

22.     private long id;  

23.       

24.     @Column(type=String.class,name="name")  

25.     private String name;  

26.   

27.   

28.     public long getId() {  

29.         return id;  

30.     }  

31.   

32.     public void setId(long id) {  

33.         this.id = id;  

34.     }  

35.   

36.     public String getName() {  

37.         return name;  

38.     }  

39.   

40.       

41.     public void setName(String name) throws SQLException {  

42.         this.name = name;  

43.         //更新数据到数据库 只有持久化的数据才可以更新操作  

44.         update("name");  

45.     }  

46.   

47.       

48. }  


ID生成

生成器

[java] view plain copy

1. package com.hc.utils;  

2.   

3. import java.util.Date;  

4. /** 

5.  * id生成 

6.  * @author chuer 

7.  * @version 2014-7-16  上午11:38:34 

8.  */  

9. public class UID {  

10.     private static Date date = new Date();  

11.     private static StringBuilder buf = new StringBuilder();  

12.     private static int seq = 0;  

13.     private static final int ROTATION = 99999;  

14.   

15.     public static synchronized long next() {  

16.         if (seq > ROTATION)  

17.             seq = 0;  

18.         buf.delete(0, buf.length());  

19.         date.setTime(System.currentTimeMillis());  

20.         String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d",  

21.                 date, seq++);  

22.         return Long.parseLong(str);  

23.     }  

24.       

25.       

26.     public static void main(String ...args){  

27.         new MyThread().start();  

28.         new MyThread().start();  

29.         new MyThread().start();  

30.         new MyThread().start();  

31.         new MyThread().start();  

32.         new MyThread().start();  

33.         new MyThread().start();  

34.         new MyThread().start();  

35.         new MyThread().start();  

36.         new MyThread().start();  

37.     }  

38. }  

39.   

40. class MyThread extends Thread{  

41.   

42.     @Override  

43.     public void run() {  

44.         for(int i=0;i<100;i++){  

45.             System.out.println(UID.next());  

46.         }  

47.     }  

48. }  


ID池

[java] view plain copy

1. package com.hc.pool;  

2.   

3. import java.util.concurrent.ConcurrentLinkedQueue;  

4.   

5. import com.hc.utils.UID;  

6. /** 

7.  * id池子 

8.  * @author chuer 

9.  * @version 2014-7-16  下午12:23:26 

10.  */  

11. public class IDPool {  

12.       

13.     private static final int MAX_POOL_SIZE = 100000;//id池大小  

14.     private static final int MIN_POOL_SIZE = 100;//id池大小  

15.     private static volatile boolean isInit = false;  

16.     private IDPool(){}  

17.     private static IDPool pool = new IDPool();  

18.     private ConcurrentLinkedQueue<Long> pools = new ConcurrentLinkedQueue<Long>();  

19.       

20.     public static IDPool getInstance(){  

21.         if(!isInit){  

22.             isInit = true;  

23.             pool.startGenerateId();  

24.         }  

25.         return pool;  

26.     }  

27.       

28.     public void  startGenerateId(){  

29.         GenerateId gi = new GenerateId();  

30.         new Thread(gi).start();  

31.     }  

32.       

33.       

34.     void addId(Long id){  

35.         pools.add(id);  

36.     }  

37.       

38.     public Long applyId(){  

39.         Long id = pools.poll();  

40.         if(id == null){  

41.             return UID.next();  

42.         }  

43.         return id;  

44.     }  

45.       

46.     class GenerateId implements Runnable{  

47.   

48.         @Override  

49.         public void run() {  

50.             while(true){  

51.                 if(pools.size()<MIN_POOL_SIZE){  

52.                     while(true){  

53.                         addId(UID.next());  

54.                         if(pools.size() == MAX_POOL_SIZE){  

55.                             break;  

56.                         }  

57.                     }  

58.                 }  

59.                   

60.                 try {  

61.                     Thread.sleep(2000);  

62.                 } catch (InterruptedException e) {  

63.                     e.printStackTrace();  

64.                 }  

65.             }  

66.               

67.         }  

68.           

69.     }  

70. }  


执行器

接口

[java] view plain copy

1. package com.hc.core;  

2.   

3. import java.sql.Connection;  

4. import java.sql.SQLException;  

5. import java.util.Collection;  

6. /** 

7.  * 增删改差接口  执行器 

8.  * @author chuer 

9.  * @date 2014-7-16 上午10:08:17 

10.  * @version V1.0 

11.  */  

12. public interface IExecute<T> {  

13.   

14.     public int save(T t) throws SQLException;  //保存操作  

15.   

16.     public int update(T t, String column) throws SQLException;  //更新操作  

17.   

18.     public int delete(T t) throws SQLException; //删除操作  

19.   

20.     public T get(T t) throws SQLException; //单个查询操作  

21.       

22.     public Collection<T> query(Class<T> cls,String sql)throws SQLException;//批量查询操作  

23.   

24.     public void execute(String sql) throws SQLException;//执行自定义sql  

25.       

26.     public void relase(Connection conn);//释放连接  

27.       

28.     public void setAutoCommit(boolean autoCommit);//设置连接是否自动提交  

29. }  

 

[java] view plain copy

1. package com.hc.core;  

2. /** 

3.  * 事务提交接口 

4.  * @author chuer 

5.  * @version 2014-7-16  上午11:27:24 

6.  */  

7. public interface ICommit {  

8.   

9.     public void commit();//提交  

10.     public void rollback();//回滚  

11.       

12. }  


抽象实现

[java] view plain copy

1. package com.hc.core;  

2.   

3. import java.sql.Connection;  

4. import java.sql.SQLException;  

5. import java.sql.Statement;  

6.   

7. import com.hc.pool.DBConfig;  

8. import com.hc.pool.DBPool;  

9.   

10. /** 

11.  * 抽象执行器 

12.  * @author chuer 

13.  * @date 2014-7-16 上午10:08:51 

14.  * @version V1.0 

15.  */  

16. public abstract class AbstractExecute<T> implements  IExecute<T>,ICommit{  

17.   

18.     protected Connection conn;  

19.     protected boolean autoCommit;  

20.       

21.     protected AbstractExecute(Connection conn){  

22.         this.conn = conn;  

23.         this.autoCommit = DBConfig.AUTOCOMMIT;  

24.     }  

25.   

26.     @Override  

27.     public void commit() {  

28.         try {  

29.             conn.commit();  

30.             relase(conn);  

31.         } catch (SQLException e) {  

32.             e.printStackTrace();  

33.         }  

34.     }  

35.   

36.     @Override  

37.     public void rollback() {  

38.         try {  

39.             conn.rollback();  

40.         } catch (SQLException e) {  

41.             e.printStackTrace();  

42.         }  

43.     }  

44.   

45.     @Override  

46.     public void relase(Connection conn) {  

47.         DBPool.getInstance().relaseConnection(conn);  

48.     }  

49.       

50.     @Override  

51.     public void execute(String sql) throws SQLException {  

52.         System.out.println(sql);  

53.         Statement stat = conn.createStatement();  

54.         stat.execute(sql);  

55.         if(autoCommit){  

56.             commit();  

57.         }  

58.     }  

59.   

60.     @Override  

61.     public void setAutoCommit(boolean autoCommit1) {  

62.         autoCommit = autoCommit1;  

63.     }  

64.       

65.       

66.       

67.       

68.       

69.       

70. }  


 

具体实现

[java] view plain copy

1. package com.hc.execute;  

2.   

3. import java.sql.Connection;  

4. import java.sql.PreparedStatement;  

5. import java.sql.ResultSet;  

6. import java.sql.SQLException;  

7. import java.sql.Statement;  

8. import java.util.ArrayList;  

9. import java.util.Collection;  

10.   

11. import com.hc.cache.CacheManager;  

12. import com.hc.core.AbstractExecute;  

13. import com.hc.core.IEntity;  

14. import com.hc.sql.SqlManager;  

15. import com.hc.utils.AssembleData;  

16. import com.hc.utils.AssembleStatement;  

17. /** 

18.  * 执行器实现类 

19.  * @author chuer 

20.  * @version 2014-7-16  上午11:36:08 

21.  * @param <T> 

22.  */  

23. public class ExecuteImpl<T extends IEntity> extends AbstractExecute<T>{  

24.   

25.     public ExecuteImpl(Connection conn){  

26.         super(conn);  

27.     }  

28.       

29.     @Override  

30.     public int save(T t) throws SQLException {  

31.         String insertSql = SqlManager.getInstance().getInsertSql(t.getClass());  

32.         System.out.println(insertSql);  

33.         PreparedStatement stat = AssembleStatement.assembleInsertSql(t, insertSql, conn);  

34.         stat.execute();  

35.         if(autoCommit){  

36.             commit();  

37.         }  

38.         CacheManager.cache(t);  

39.         return 0;  

40.     }  

41.   

42.     @Override  

43.     public int update(T t,String column) throws SQLException {  

44.         String updateSql = SqlManager.getInstance().getUpdateSql(t.getClass(),column);  

45.         System.out.println(updateSql);  

46.         PreparedStatement stat = AssembleStatement.assembleUpdateSql(t, updateSql, conn, column);  

47.         stat.execute();  

48.         if(autoCommit){  

49.             commit();  

50.         }  

51.         return 0;  

52.     }  

53.   

54.     @Override  

55.     public int delete(T t) throws SQLException {  

56.         String deleteSql = SqlManager.getInstance().getDeleteSql(t.getClass());  

57.         System.out.println(deleteSql);  

58.         PreparedStatement stat = AssembleStatement.assembleDeleteSql(t, deleteSql, conn);  

59.         stat.execute();  

60.         if(autoCommit){  

61.             commit();  

62.         }  

63.         return 0;  

64.     }  

65.   

66.     @Override  

67.     public T get(T t) throws SQLException {  

68.         String singleSql = SqlManager.getInstance().getSingleSql(t.getClass());  

69.         System.out.println(singleSql);  

70.         PreparedStatement stat = AssembleStatement.assembleSingleSql(t, singleSql, conn);  

71.         ResultSet rs = stat.executeQuery();  

72.         try {  

73.             AssembleData.assembleSingle(t, rs);  

74.         } catch (Exception e) {  

75.             e.printStackTrace();  

76.         }  

77.         if(autoCommit){  

78.             commit();  

79.         }  

80.         return t;  

81.     }  

82.   

83.     @Override  

84.     public Collection<T> query(Class<T> cls,String condition)throws SQLException {  

85.         String querySql = SqlManager.getInstance().getQuerySql(cls);  

86.         querySql += condition;  

87.         System.out.println(querySql);  

88.         Statement stat = conn.createStatement();  

89.         ResultSet rs = stat.executeQuery(querySql);  

90.         Collection<T> list = null;  

91.         try {  

92.             list = AssembleData.assembleCollection(new ArrayList<T>(), cls, rs);  

93.         } catch (Exception e) {  

94.             e.printStackTrace();  

95.         }  

96.         if(autoCommit){  

97.             commit();  

98.         }  

99.         return list;  

100.     }  

101.   

102.   

103.       

104.       

105.   

106.       

107. }  


 

装配器:

[java] view plain copy

1. package com.hc.utils;  

2.   

3. import java.lang.reflect.Field;  

4. import java.lang.reflect.Method;  

5. import java.sql.Connection;  

6. import java.sql.PreparedStatement;  

7. import java.sql.SQLException;  

8.   

9. import com.hc.annotation.Column;  

10. /** 

11.  * sql装配 

12.  * @author chuer 

13.  * @version 2014-7-16  上午10:13:05 

14.  */  

15. public class AssembleStatement {  

16.   

17.       

18.     /** 

19.      * 装配单个查询sql 

20.      * @param t 

21.      * @param sql 

22.      * @param conn 

23.      * @return 

24.      */  

25.     public static <T> PreparedStatement assembleSingleSql(T t,String sql,Connection conn){  

26.         try{  

27.             PreparedStatement pStat= conn.prepareStatement(sql);  

28.             Field[] fields = t.getClass().getDeclaredFields();  

29.             for(Field fie : fields){  

30.                 if(fie.isAnnotationPresent(Column.class)){  

31.                     Column annotation = fie.getAnnotation(Column.class);  

32.                     if(annotation.isPrimary()){  

33.                         Object id = getColumnValue(fie.getName(), t);  

34.                         fill(annotation,pStat,1,id);  

35.                         break;  

36.                     }  

37.                 }  

38.             }  

39.             return pStat;  

40.         }catch(Exception e){  

41.             e.printStackTrace();  

42.         }  

43.         return null;  

44.     }  

45.     /** 

46.      * 装配删除sql 

47.      * @param t 

48.      * @param sql 

49.      * @param conn 

50.      * @return 

51.      */  

52.     public static <T> PreparedStatement assembleDeleteSql(T t,String sql,Connection conn){  

53.         try{  

54.             PreparedStatement pStat= conn.prepareStatement(sql);  

55.             Field[] fields = t.getClass().getDeclaredFields();  

56.             for(Field fie : fields){  

57.                 if(fie.isAnnotationPresent(Column.class)){  

58.                     Column annotation = fie.getAnnotation(Column.class);  

59.                     if(annotation.isPrimary()){  

60.                         Object id = getColumnValue(fie.getName(), t);  

61.                         fill(annotation,pStat,1,id);  

62.                         break;  

63.                     }  

64.                 }  

65.             }  

66.             return pStat;  

67.         }catch(Exception e){  

68.             e.printStackTrace();  

69.         }  

70.         return null;  

71.     }  

72.     /** 

73.      * 装配更新sql 

74.      * @param t 

75.      * @param sql 

76.      * @param conn 

77.      * @param columnName 

78.      * @return 

79.      */  

80.     public static <T> PreparedStatement assembleUpdateSql(T t,String sql,Connection conn,String columnName){  

81.         try{  

82.             PreparedStatement pStat= conn.prepareStatement(sql);  

83.             Object value = getColumnValue(columnName, t);  

84.             Field field = t.getClass().getDeclaredField(columnName);  

85.             fill(field.getAnnotation(Column.class),pStat,1,value);  

86.               

87.               

88.             Field[] fields = t.getClass().getDeclaredFields();  

89.             for(Field fie : fields){  

90.                 if(fie.isAnnotationPresent(Column.class)){  

91.                     Column annotation = fie.getAnnotation(Column.class);  

92.                     if(annotation.isPrimary()){  

93.                         Object id = getColumnValue(fie.getName(), t);  

94.                         fill(annotation,pStat,2,id);  

95.                         break;  

96.                     }  

97.                 }  

98.             }  

99.             return pStat;  

100.         }catch(Exception e){  

101.             e.printStackTrace();  

102.         }  

103.         return null;  

104.     }  

105.       

106.     /** 

107.      * 装配插入sql 

108.      * @param t 

109.      * @param sql 

110.      * @param conn 

111.      * @return 

112.      * @throws SQLException 

113.      */  

114.     public static <T> PreparedStatement assembleInsertSql(T t,String sql,Connection conn)throws SQLException{  

115.         try{  

116.             PreparedStatement pStat= conn.prepareStatement(sql);  

117.             Field [] fileds = t.getClass().getDeclaredFields();  

118.             for(int i=0;i<fileds.length;i++){  

119.                 Field field = fileds[i];  

120.                 if(field.isAnnotationPresent(Column.class)){  

121.                     Object value = getColumnValue(field.getName(),t);  

122.                     fill(field.getAnnotation(Column.class),pStat,i+1,value);  

123.                 }  

124.             }  

125.             return pStat;  

126.         }catch(Exception e){  

127.             e.printStackTrace();  

128.         }  

129.         return null;  

130.     }  

131.       

132.     /** 

133.      * 得到字段的值 

134.      * @param columnName 

135.      * @param t 

136.      * @return 

137.      * @throws Exception 

138.      */  

139.     private static <T>  Object getColumnValue(String columnName,T t)throws Exception{  

140.         String methodName = "get"+columnName.substring(0,1).toUpperCase()+columnName.substring(1, columnName.length());  

141.         Method method = t.getClass().getMethod(methodName, new Class[]{});  

142.         Object value = method.invoke(t, new Object[]{});  

143.         return value;  

144.     }  

145.     /** 

146.      * 替换sql中的? 

147.      * @param ctype 

148.      * @param pStat 

149.      * @param index 

150.      * @param value 

151.      * @throws Exception 

152.      */  

153.     private static void fill(Column ctype,PreparedStatement pStat,int index,Object value)throws Exception{  

154.         Class<? extends Object> type = ctype.type();  

155.         if(type == int.class){  

156.             pStat.setInt(index, (int)value);  

157.         }else if(type == byte.class){  

158.             pStat.setByte(index, (byte)value);  

159.         }else if(type == short.class){  

160.             pStat.setShort(index, (short)value);  

161.         }else if(type == long.class){  

162.             pStat.setLong(index, (long)value);  

163.         }else if(type == String.class){  

164.             pStat.setString(index, (String)value);  

165.         }  

166.     }  

167. }  


 

[java] view plain copy

1. package com.hc.utils;  

2.   

3. import java.lang.reflect.Field;  

4. import java.lang.reflect.Method;  

5. import java.sql.ResultSet;  

6. import java.util.Collection;  

7.   

8. import com.hc.annotation.Column;  

9. import com.hc.core.EntityStatus;  

10.   

11. public class AssembleData {  

12.   

13.     /** 

14.      * 返回集合 

15.      * @param list 

16.      * @param cls 

17.      * @param rs 

18.      * @return 

19.      * @throws Exception 

20.      */  

21.     public static <T> Collection<T> assembleCollection(Collection<T> list,Class<T> cls,ResultSet rs)throws Exception{  

22.         while(rs.next()){  

23.             T instance = cls.getConstructor(new Class[]{}).newInstance(new Object[]{});  

24.             assemble(instance,rs);  

25.             list.add(instance);  

26.         }  

27.         return list;  

28.     }  

29.       

30.     private  static <T> T assemble(T t,ResultSet rs) throws Exception{  

31.         Method method = t.getClass().getMethod("setStatus", new Class[]{EntityStatus.class});  

32.         method.invoke(t, new Object[]{EntityStatus.QUERY});  

33.         Field[] declaredFields = t.getClass().getDeclaredFields();  

34.         for(Field field : declaredFields){  

35.             if(field.isAnnotationPresent(Column.class)){  

36.                 Column annotation = field.getAnnotation(Column.class);  

37.                   

38.                 String fieldName = field.getName();  

39.                 String ColumnName = annotation.name();  

40.                 Class<?> type = annotation.type();  

41.                 setValue(t,type,rs,ColumnName,fieldName);  

42.             }  

43.         }  

44.         method.invoke(t, new Object[]{EntityStatus.PERSIST});  

45.         return t;  

46.     }  

47.     /** 

48.      * 返回单对象 

49.      * @param t 

50.      * @param rs 

51.      * @return 

52.      * @throws Exception 

53.      */  

54.     public static <T> T assembleSingle(T t,ResultSet rs) throws Exception{  

55.         if(rs.next()){  

56.             Field[] declaredFields = t.getClass().getDeclaredFields();  

57.             for(Field field : declaredFields){  

58.                 if(field.isAnnotationPresent(Column.class)){  

59.                     Column annotation = field.getAnnotation(Column.class);  

60.                       

61.                     String fieldName = field.getName();  

62.                     String ColumnName = annotation.name();  

63.                     Class<?> type = annotation.type();  

64.                     setValue(t,type,rs,ColumnName,fieldName);  

65.                 }  

66.             }  

67.         }  

68.         return t;  

69.     }  

70.       

71.     private static <T,S> void setValue(T t,Class<S> type,ResultSet rs,String columnName,String fieldName)throws Exception{  

72.         String setMethodName = "set"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);  

73.         Method setMethod = t.getClass().getMethod(setMethodName, new Class[]{type});  

74.         if(type == int.class){  

75.             setMethod.invoke(t, new Object[]{rs.getInt(columnName)});  

76.         }else if(type == byte.class){  

77.             setMethod.invoke(t, new Object[]{rs.getByte(columnName)});  

78.         }else if(type == short.class){  

79.             setMethod.invoke(t, new Object[]{rs.getShort(columnName)});  

80.         }else if(type == long.class){  

81.             setMethod.invoke(t, new Object[]{rs.getLong(columnName)});  

82.         }else if(type == String.class){  

83.             setMethod.invoke(t, new Object[]{rs.getString(columnName)});  

84.         }  

85.     }  

86.       

87. }  


工具类Query

[java] view plain copy

1. package com.hc.utils;  

2.   

3. import java.lang.reflect.InvocationTargetException;  

4. import java.sql.SQLException;  

5. import java.util.Collection;  

6.   

7. import com.hc.cache.CacheManager;  

8. import com.hc.core.AbstractExecute;  

9. import com.hc.core.ExecuteFactory;  

10. import com.hc.core.IEntity;  

11.   

12. public class Query {  

13.       

14.     public static <T extends IEntity> Collection<T> query(Class<T> cls,String condition) throws SQLException{  

15.         AbstractExecute<T> execute = ExecuteFactory.getExecute();  

16.         return execute.query(cls, condition);  

17.     }  

18.       

19.       

20.     public static IEntity load(Class<?> cls,long id) throws SQLException {  

21.         IEntity entity = CacheManager.getEntity(cls.toString()+id);  

22.         if(entity != null){  

23.             return entity;  

24.         }  

25.         IEntity newInstance = null;  

26.         try {  

27.             newInstance = (IEntity)cls.getConstructor(new Class[]{}).newInstance(new Object[]{});  

28.         } catch (InstantiationException | IllegalAccessException  

29.                 | IllegalArgumentException | InvocationTargetException  

30.                 | NoSuchMethodException | SecurityException e) {  

31.             e.printStackTrace();  

32.         }  

33.         newInstance.get(id);  

34.         return newInstance;  

35.     }  

36.       

37.     public static void execute(String sql)throws SQLException{  

38.         AbstractExecute<IEntity> execute = ExecuteFactory.getExecute();  

39.         execute.execute(sql);  

40.     }  

41.       

42. }  


测试类

[java] view plain copy

1. package com.hc.execute;  

2.   

3. import com.hc.pool.IDPool;  

4. import com.hc.sample.entity.UserEntity;  

5.   

6. public class TestExecute {  

7.   

8.     /** 

9.      * @param args 

10.      */  

11.     public static void main(String[] args) throws Exception{  

12.           

13.         UserEntity user  = new UserEntity();  

14.         Long applyId = IDPool.getInstance().applyId();  

15.         user.setId(applyId);  

16.           

17.           

18.         user.setName("chujiinhui");  

19.           

20.         //持久化用户  

21.         user.persist();  

22.           

23.           

24.         //查询此用户  

25.         user = (UserEntity)user.get(applyId);  

26.         System.out.println(user.getName());  

27.           

28.           

29.         //更新此用户  

30.         user.setName("hello");  

31.           

32.           

33.         user = (UserEntity)user.get(applyId);  

34.         System.out.println(user.getName());  

35.           

36.           

37.     }  

38.   

39. }  


 

运行结果如下:

 

[plain] view plain copy

1. insert into user_m(id,name) values (?,?)  

2. select * from user_m where 1=1 and id=?  

3. chujiinhui  

4. update user_m set name=? where id=?  

5. select * from user_m where 1=1 and id=?  

6. hello  


查看数据库也存在已添加的数据。

本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言VC/MFC频道!


本文由 @小职 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程