jdbc简易泛型dao

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/wangpeng047/article/details/8615843

一、实现思路

1、定义3个Annotation(注解):Entity、Id、Column,Entity作用于Type级别,用于标识JavaBean与数据库表名的映射关系。Id作用于Field级别,用于标识JavaBean中ID属性与表中ID字段的映射关系,Column作用于Field级别,用于标识JavaBean中除ID属性外的其它属性与表中字段的映射关系。

2、在Dao实现类中,通过反射API获得JavaBean中注解和属性的信息,如:表名、字段。JavaBean属性的名称、数据类型等信息。然后将这些信息拼接成一条SQL语句,通过JDBC的方式与数据库交互。

二、示例代码

1、定义一个Dao公共类,提供获得数据库连接与释放数据库资源的接口

 
 
  1. package dao;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. /**
  8. * 提供获取数据库连接、释放资源的接口
  9. */
  10. public class JdbcDaoHelper {
  11. /**
  12. * 数据库用户名
  13. */
  14. private static final String USER = "test";
  15. /**
  16. * 数据库密码
  17. */
  18. private static final String PASSWORD = "test";
  19. /**
  20. * 连接数据库的地址
  21. */
  22. private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:study";
  23. private static Connection conn;
  24. /**
  25. * 获得一个数据库连接对象
  26. * @return java.sql.Connection实例
  27. */
  28. public static Connection getConnection() {
  29. try {
  30. if (conn == null) {
  31. Class.forName( "oracle.jdbc.OracleDriver");
  32. conn = DriverManager.getConnection(URL, USER, PASSWORD);
  33. } else {
  34. return conn;
  35. }
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. return conn;
  40. }
  41. /**
  42. * 释放数据库资源
  43. */
  44. public static void release(PreparedStatement ps,ResultSet rs) {
  45. try {
  46. if (conn != null) {
  47. conn.close();
  48. conn = null;
  49. }
  50. if (ps != null) {
  51. ps.close();
  52. ps = null;
  53. }
  54. if (rs != null) {
  55. rs.close();
  56. rs = null;
  57. }
  58. } catch (SQLException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. }
2、定义一个泛型Dao接口GenericDao<T>

 
 
  1. package dao;
  2. import java.util.List;
  3. import java.util.Map;
  4. public interface GenericDao<T> {
  5. public void save(T t) throws Exception;
  6. public void delete(Object id,Class<T> clazz) throws Exception;
  7. public void update(T t) throws Exception;
  8. public T get(Object id,Class<T> clazz) throws Exception;
  9. /**
  10. * 根据条件查询
  11. * @param sqlWhereMap key:条件字段名 value:条件字段值
  12. * @param clazz
  13. * @return
  14. * @throws Exception
  15. */
  16. public List<T> findAllByConditions(Map<String,Object> sqlWhereMap,Class<T> clazz) throws Exception;
  17. }
3、定义GenericDao<T>接口JDBC实现类JdbcGenericDaoImpl<T>

 
 
  1. package dao;
  2. import java.beans.IntrospectionException;
  3. import java.beans.PropertyDescriptor;
  4. import java.lang.reflect.Field;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.sql.Timestamp;
  10. import java.sql.Types;
  11. import java.util.ArrayList;
  12. import java.util.Date;
  13. import java.util.HashMap;
  14. import java.util.Iterator;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Set;
  18. import java.util.Map.Entry;
  19. import annotation.Column;
  20. import annotation.Entity;
  21. import annotation.Id;
  22. import exception.NotFoundAnnotationException;
  23. /**
  24. * 泛型DAO的JDBC实现
  25. * @author 杨信
  26. * @version 1.0
  27. */
  28. public class JdbcGenericDaoImpl<T> implements GenericDao<T> {
  29. //表的别名
  30. private static final String TABLE_ALIAS = "t";
  31. @Override
  32. public void save(T t) throws Exception {
  33. Class<?> clazz = t.getClass();
  34. //获得表名
  35. String tableName = getTableName(clazz);
  36. //获得字段
  37. StringBuilder fieldNames = new StringBuilder(); //字段名
  38. List<Object> fieldValues = new ArrayList<Object>(); //字段值
  39. StringBuilder placeholders = new StringBuilder(); //占位符
  40. Field[] fields = clazz.getDeclaredFields();
  41. for (Field field : fields) {
  42. PropertyDescriptor pd = new PropertyDescriptor(field.getName(),t.getClass());
  43. if (field.isAnnotationPresent(Id.class)) {
  44. fieldNames.append(field.getAnnotation(Id.class).value()).append( ",");
  45. fieldValues.add(pd.getReadMethod().invoke(t));
  46. } else if(field.isAnnotationPresent(Column.class)) {
  47. fieldNames.append(field.getAnnotation(Column.class).value()).append( ",");
  48. fieldValues.add(pd.getReadMethod().invoke(t));
  49. }
  50. placeholders.append( "?").append( ",");
  51. }
  52. //删除最后一个逗号
  53. fieldNames.deleteCharAt(fieldNames.length()- 1);
  54. placeholders.deleteCharAt(placeholders.length()- 1);
  55. //拼接sql
  56. StringBuilder sql = new StringBuilder( "");
  57. sql.append( "insert into ").append(tableName)
  58. .append( " (").append(fieldNames.toString())
  59. .append( ") values (").append(placeholders).append( ")") ;
  60. PreparedStatement ps = JdbcDaoHelper.getConnection().prepareStatement(sql.toString());
  61. //设置SQL参数占位符的值
  62. setParameter(fieldValues, ps, false);
  63. //执行SQL
  64. ps.execute();
  65. JdbcDaoHelper.release(ps, null);
  66. System.out.println(sql + "\n" + clazz.getSimpleName() + "添加成功!");
  67. }
  68. @Override
  69. public void delete(Object id,Class<T> clazz) throws Exception {
  70. //获得表名
  71. String tableName = getTableName(clazz);
  72. //获得ID字段名和值
  73. String idFieldName = "";
  74. boolean flag = false;
  75. Field[] fields = clazz.getDeclaredFields();
  76. for (Field field : fields) {
  77. if(field.isAnnotationPresent(Id.class)) {
  78. idFieldName = field.getAnnotation(Id.class).value();
  79. flag = true;
  80. break;
  81. }
  82. }
  83. if (!flag) {
  84. throw new NotFoundAnnotationException(clazz.getName() + " object not found id property.");
  85. }
  86. //拼装sql
  87. String sql = "delete from " + tableName + " where " + idFieldName + "=?";
  88. PreparedStatement ps = JdbcDaoHelper.getConnection().prepareStatement(sql);
  89. ps.setObject( 1, id);
  90. //执行SQL
  91. ps.execute();
  92. JdbcDaoHelper.release(ps, null);
  93. System.out.println(sql + "\n" + clazz.getSimpleName() + "删除成功!");
  94. }
  95. @Override
  96. public void update(T t) throws Exception {
  97. Class<?> clazz = t.getClass();
  98. //获得表名
  99. String tableName = getTableName(clazz);
  100. //获得字段
  101. List<Object> fieldNames = new ArrayList<Object>(); //字段名
  102. List<Object> fieldValues = new ArrayList<Object>(); //字段值
  103. List<String> placeholders = new ArrayList<String>(); //占位符
  104. String idFieldName = "";
  105. Object idFieldValue = "";
  106. Field[] fields = clazz.getDeclaredFields();
  107. for (Field field : fields) {
  108. PropertyDescriptor pd = new PropertyDescriptor(field.getName(),t.getClass());
  109. if (field.isAnnotationPresent(Id.class)) {
  110. idFieldName = field.getAnnotation(Id.class).value();
  111. idFieldValue = pd.getReadMethod().invoke(t);
  112. } else if(field.isAnnotationPresent(Column.class)) {
  113. fieldNames.add(field.getAnnotation(Column.class).value());
  114. fieldValues.add(pd.getReadMethod().invoke(t));
  115. placeholders.add( "?");
  116. }
  117. }
  118. //ID作为更新条件,放在集合中的最后一个元素
  119. fieldNames.add(idFieldName);
  120. fieldValues.add(idFieldValue);
  121. placeholders.add( "?");
  122. //拼接sql
  123. StringBuilder sql = new StringBuilder( "");
  124. sql.append( "update ").append(tableName).append( " set ");
  125. int index = fieldNames.size() - 1;
  126. for ( int i = 0; i < index; i++) {
  127. sql.append(fieldNames.get(i)).append( "=").append(placeholders.get(i)).append( ",");
  128. }
  129. sql.deleteCharAt(sql.length()- 1).append( " where ").append(fieldNames.get(index)).append( "=").append( "?");
  130. //设置SQL参数占位符的值
  131. PreparedStatement ps = JdbcDaoHelper.getConnection().prepareStatement(sql.toString());
  132. setParameter(fieldValues, ps, false);
  133. //执行SQL
  134. ps.execute();
  135. JdbcDaoHelper.release(ps, null);
  136. System.out.println(sql + "\n" + clazz.getSimpleName() + "修改成功.");
  137. }
  138. @Override
  139. public T get(Object id,Class<T> clazz) throws Exception {
  140. String idFieldName = "";
  141. Field[] fields = clazz.getDeclaredFields();
  142. boolean flag = false;
  143. for (Field field : fields) {
  144. if (field.isAnnotationPresent(Id.class)) {
  145. idFieldName = field.getAnnotation(Id.class).value();
  146. flag = true;
  147. break;
  148. }
  149. }
  150. if (!flag) {
  151. throw new NotFoundAnnotationException(clazz.getName() + " object not found id property.");
  152. }
  153. //拼装SQL
  154. Map<String,Object> sqlWhereMap = new HashMap<String, Object>();
  155. sqlWhereMap.put(TABLE_ALIAS + "." + idFieldName, id);
  156. List<T> list = findAllByConditions(sqlWhereMap, clazz);
  157. return list.size() > 0 ? list.get( 0) : null;
  158. }
  159. @Override
  160. public List<T> findAllByConditions(Map<String,Object> sqlWhereMap,Class<T> clazz) throws Exception {
  161. List<T> list = new ArrayList<T>();
  162. String tableName = getTableName(clazz);
  163. String idFieldName = "";
  164. //存储所有字段的信息
  165. //通过反射获得要查询的字段
  166. StringBuffer fieldNames = new StringBuffer();
  167. Field[] fields = clazz.getDeclaredFields();
  168. for (Field field : fields) {
  169. String propertyName = field.getName();
  170. if (field.isAnnotationPresent(Id.class)) {
  171. idFieldName = field.getAnnotation(Id.class).value();
  172. fieldNames.append(TABLE_ALIAS + "." + idFieldName)
  173. .append( " as ").append(propertyName).append( ",");
  174. } else if (field.isAnnotationPresent(Column.class)) {
  175. fieldNames.append(TABLE_ALIAS + "." + field.getAnnotation(Column.class).value())
  176. .append( " as ").append(propertyName).append( ",");
  177. }
  178. }
  179. fieldNames.deleteCharAt(fieldNames.length()- 1);
  180. //拼装SQL
  181. String sql = "select " + fieldNames + " from " + tableName + " " + TABLE_ALIAS;
  182. PreparedStatement ps = null;
  183. List<Object> values = null;
  184. if (sqlWhereMap != null) {
  185. List<Object> sqlWhereWithValues = getSqlWhereWithValues(sqlWhereMap);
  186. if (sqlWhereWithValues != null) {
  187. //拼接SQL条件
  188. String sqlWhere = (String)sqlWhereWithValues.get( 0);
  189. sql += sqlWhere;
  190. //得到SQL条件中占位符的值
  191. values = (List<Object>) sqlWhereWithValues.get( 1);
  192. }
  193. }
  194. //设置参数占位符的值
  195. if (values != null) {
  196. ps = JdbcDaoHelper.getConnection().prepareStatement(sql);
  197. setParameter(values, ps, true);
  198. } else {
  199. ps = JdbcDaoHelper.getConnection().prepareStatement(sql);
  200. }
  201. //执行SQL
  202. ResultSet rs = ps.executeQuery();
  203. while(rs.next()) {
  204. T t = clazz.newInstance();
  205. initObject(t, fields, rs);
  206. list.add(t);
  207. }
  208. //释放资源
  209. JdbcDaoHelper.release(ps, rs);
  210. System.out.println(sql);
  211. return list;
  212. }
  213. /**
  214. * 根据结果集初始化对象
  215. */
  216. private void initObject(T t, Field[] fields, ResultSet rs)
  217. throws SQLException, IntrospectionException,
  218. IllegalAccessException, InvocationTargetException {
  219. for (Field field : fields) {
  220. String propertyName = field.getName();
  221. Object paramVal = null;
  222. Class<?> clazzField = field.getType();
  223. if (clazzField == String.class) {
  224. paramVal = rs.getString(propertyName);
  225. } else if (clazzField == short.class || clazzField == Short.class) {
  226. paramVal = rs.getShort(propertyName);
  227. } else if (clazzField == int.class || clazzField == Integer.class) {
  228. paramVal = rs.getInt(propertyName);
  229. } else if (clazzField == long.class || clazzField == Long.class) {
  230. paramVal = rs.getLong(propertyName);
  231. } else if (clazzField == float.class || clazzField == Float.class) {
  232. paramVal = rs.getFloat(propertyName);
  233. } else if (clazzField == double.class || clazzField == Double.class) {
  234. paramVal = rs.getDouble(propertyName);
  235. } else if (clazzField == boolean.class || clazzField == Boolean.class) {
  236. paramVal = rs.getBoolean(propertyName);
  237. } else if (clazzField == byte.class || clazzField == Byte.class) {
  238. paramVal = rs.getByte(propertyName);
  239. } else if (clazzField == char.class || clazzField == Character.class) {
  240. paramVal = rs.getCharacterStream(propertyName);
  241. } else if (clazzField == Date.class) {
  242. paramVal = rs.getTimestamp(propertyName);
  243. } else if (clazzField.isArray()) {
  244. paramVal = rs.getString(propertyName).split( ","); //以逗号分隔的字符串
  245. }
  246. PropertyDescriptor pd = new PropertyDescriptor(propertyName,t.getClass());
  247. pd.getWriteMethod().invoke(t, paramVal);
  248. }
  249. }
  250. /**
  251. * 根据条件,返回sql条件和条件中占位符的值
  252. * @param sqlWhereMap key:字段名 value:字段值
  253. * @return 第一个元素为SQL条件,第二个元素为SQL条件中占位符的值
  254. */
  255. private List<Object> getSqlWhereWithValues(Map<String,Object> sqlWhereMap) {
  256. if (sqlWhereMap.size() < 1 ) return null;
  257. List<Object> list = new ArrayList<Object>();
  258. List<Object> fieldValues = new ArrayList<Object>();
  259. StringBuffer sqlWhere = new StringBuffer( " where ");
  260. Set<Entry<String, Object>> entrySets = sqlWhereMap.entrySet();
  261. for (Iterator<Entry<String, Object>> iteraotr = entrySets.iterator();iteraotr.hasNext();) {
  262. Entry<String, Object> entrySet = iteraotr.next();
  263. fieldValues.add(entrySet.getValue());
  264. Object value = entrySet.getValue();
  265. if (value.getClass() == String.class) {
  266. sqlWhere.append(entrySet.getKey()).append( " like ").append( "?").append( " and ");
  267. } else {
  268. sqlWhere.append(entrySet.getKey()).append( "=").append( "?").append( " and ");
  269. }
  270. }
  271. sqlWhere.delete(sqlWhere.lastIndexOf( "and"), sqlWhere.length());
  272. list.add(sqlWhere.toString());
  273. list.add(fieldValues);
  274. return list;
  275. }
  276. /**
  277. * 获得表名
  278. */
  279. private String getTableName(Class<?> clazz) throws NotFoundAnnotationException {
  280. if (clazz.isAnnotationPresent(Entity.class)) {
  281. Entity entity = clazz.getAnnotation(Entity.class);
  282. return entity.value();
  283. } else {
  284. throw new NotFoundAnnotationException(clazz.getName() + " is not Entity Annotation.");
  285. }
  286. }
  287. /**
  288. * 设置SQL参数占位符的值
  289. */
  290. private void setParameter(List<Object> values, PreparedStatement ps, boolean isSearch)
  291. throws SQLException {
  292. for ( int i = 1; i <= values.size(); i++) {
  293. Object fieldValue = values.get(i- 1);
  294. Class<?> clazzValue = fieldValue.getClass();
  295. if (clazzValue == String.class) {
  296. if (isSearch)
  297. ps.setString(i, "%" + (String)fieldValue + "%");
  298. else
  299. ps.setString(i,(String)fieldValue);
  300. } else if (clazzValue == boolean.class || clazzValue == Boolean.class) {
  301. ps.setBoolean(i, (Boolean)fieldValue);
  302. } else if (clazzValue == byte.class || clazzValue == Byte.class) {
  303. ps.setByte(i, (Byte)fieldValue);
  304. } else if (clazzValue == char.class || clazzValue == Character.class) {
  305. ps.setObject(i, fieldValue,Types.CHAR);
  306. } else if (clazzValue == Date.class) {
  307. ps.setTimestamp(i, new Timestamp(((Date) fieldValue).getTime()));
  308. } else if (clazzValue.isArray()) {
  309. Object[] arrayValue = (Object[]) fieldValue;
  310. StringBuffer sb = new StringBuffer();
  311. for ( int j = 0; j < arrayValue.length; j++) {
  312. sb.append(arrayValue[j]).append( "、");
  313. }
  314. ps.setString(i, sb.deleteCharAt(sb.length()- 1).toString());
  315. } else {
  316. ps.setObject(i, fieldValue, Types.NUMERIC);
  317. }
  318. }
  319. }
  320. }
4、定义三个注解Entity、Id、Column,生命周期保存在运行期间,以便通过反射获取

1)、Entity


 
 
  1. package annotation;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * 数据库表的的名称
  8. */
  9. @Retention(RetentionPolicy.RUNTIME)
  10. @Target(ElementType.TYPE)
  11. public @interface Entity {
  12. /**
  13. * 表名
  14. */
  15. String value();
  16. }

2)、Id


 
 
  1. package annotation;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * 标识数据库字段的ID
  8. */
  9. @Retention(RetentionPolicy.RUNTIME)
  10. @Target(ElementType.FIELD)
  11. public @interface Id {
  12. /**
  13. * ID的名称
  14. * @return
  15. */
  16. String value();
  17. }

3)、Column


 
 
  1. package annotation;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * 标识数据库字段的名称
  8. * @author 杨信
  9. *
  10. */
  11. @Retention(RetentionPolicy.RUNTIME)
  12. @Target(ElementType.FIELD)
  13. public @interface Column {
  14. /**
  15. * 字段名称
  16. */
  17. String value();
  18. /**
  19. * 字段的类型
  20. * @return
  21. */
  22. Class<?> type() default String.class;
  23. /**
  24. * 字段的长度
  25. * @return
  26. */
  27. int length() default 0;
  28. }
5、定义一个JavaBean,用于测试使用

要求:

1)、类名必须用Entity注解标识,并指定数据库中对应的表名

2)、Id属性必须用Id注解标识,并指定表中所对应的字段名

3)、其它属性必须用Column注解标识,并指定表中所对应的字段名

4)、JavaBean属性的数据类型目前只实现了8大基本数据类型、String和这些基本类型的数组类型。

5)、JavaBean属性目前没有做字段的长度与类型的判断,待以后改进。


 
 
  1. package model;
  2. import java.util.Date;
  3. import annotation.Column;
  4. import annotation.Entity;
  5. import annotation.Id;
  6. /**
  7. * 图书
  8. */
  9. @Entity( "t_book") //表名
  10. public class Book {
  11. /**
  12. * 图书编号
  13. */
  14. @Id( "t_isbn")
  15. private String isbn;
  16. /**
  17. * 书名
  18. */
  19. @Column( "t_name")
  20. private String name;
  21. /**
  22. * 作者
  23. */
  24. @Column( "t_author")
  25. private String author;
  26. /**
  27. * 出版社
  28. */
  29. @Column( "t_publishing")
  30. private String publishing;
  31. /**
  32. * 出版时间
  33. */
  34. @Column(value = "t_pubdate")
  35. private Date pubdate;
  36. /**
  37. * 价格
  38. */
  39. @Column(value = "t_price")
  40. private double price;
  41. public String getIsbn() {
  42. return isbn;
  43. }
  44. public void setIsbn(String isbn) {
  45. this.isbn = isbn;
  46. }
  47. public String getName() {
  48. return name;
  49. }
  50. public void setName(String name) {
  51. this.name = name;
  52. }
  53. public String getAuthor() {
  54. return author;
  55. }
  56. public void setAuthor(String author) {
  57. this.author = author;
  58. }
  59. public String getPublishing() {
  60. return publishing;
  61. }
  62. public void setPublishing(String publishing) {
  63. this.publishing = publishing;
  64. }
  65. public Date getPubdate() {
  66. return pubdate;
  67. }
  68. public void setPubdate(Date pubdate) {
  69. this.pubdate = pubdate;
  70. }
  71. public double getPrice() {
  72. return price;
  73. }
  74. public void setPrice(double price) {
  75. this.price = price;
  76. }
  77. @Override
  78. public String toString() {
  79. return "书名: " + name + " 图书编号: " + isbn + " 作者: " + author
  80. + " 出版社: " + publishing + " 出版时间: " + pubdate
  81. + " 价格: " + price;
  82. }
  83. }
6、使用Junit4进行单元测试

 
 
  1. package xml;
  2. import java.io.InputStream;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import model.Book;
  7. import org.junit.BeforeClass;
  8. import org.junit.Test;
  9. import util.DateUtils;
  10. import dao.GenericDao;
  11. import dao.JdbcGenericDaoImpl;
  12. /**
  13. * 测试泛型DAO的CRUD操作
  14. */
  15. public class GenericDaoTest {
  16. private GenericDao<Book> bookDao = new JdbcGenericDaoImpl<Book>();
  17. private static InputStream is;
  18. @BeforeClass
  19. public static void setUpBeforeClass() throws Exception {
  20. is = XmlParserTest.class.getResourceAsStream( "/books.xml");
  21. }
  22. @Test
  23. public void testSave() throws Exception {
  24. List<Book> books = SaxHelper.saxReader(is);
  25. for (Book book : books) {
  26. bookDao.save(book);
  27. }
  28. }
  29. @Test
  30. public void testStudentFindAll1() throws Exception {
  31. System.out.println( "\n-------------更新、删除前,测试查询所有记录--------------------");
  32. List<Book> books = bookDao.findAllByConditions( null, Book.class);
  33. for (Book book : books) {
  34. System.out.println(book);
  35. }
  36. }
  37. @Test
  38. public void testDelete() throws Exception {
  39. System.out.println( "\n-------------测试删除一条记录--------------------");
  40. bookDao.delete( "9787111349662",Book.class);
  41. }
  42. @Test
  43. public void testGet() throws Exception {
  44. System.out.println( "\n-------------测试查询一条记录--------------------");
  45. Book book = bookDao.get( "9787121025389", Book.class);
  46. System.out.println(book);
  47. }
  48. @Test
  49. public void testUpdate() throws Exception {
  50. System.out.println( "\n-------------测试修改一条记录--------------------");
  51. Book book = new Book();
  52. book.setIsbn( "9787121025389");
  53. book.setName( "JAVA面向对象编程");
  54. book.setAuthor( "孙卫琴");
  55. book.setPublishing( "电子工业出版社");
  56. book.setPubdate(DateUtils.string2Date( "yyyy-MM-dd", "2006-07-01"));
  57. book.setPrice( 50.6);
  58. bookDao.update(book);
  59. }
  60. @Test
  61. public void testStudentFindAll2() throws Exception {
  62. System.out.println( "\n-------------更新、删除前,测试根据条件查询所有记录--------------------");
  63. Map<String,Object> sqlWhereMap = new HashMap<String, Object>();
  64. //sqlWhereMap.put("t_isbn", "9787111213826");
  65. //sqlWhereMap.put("t_name", "Java");
  66. sqlWhereMap.put( "t_publishing", "机械工业出版社");
  67. //sqlWhereMap.put("t_pubdate", new Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2007-01-01 12:06:00").getTime()));
  68. List<Book> books = bookDao.findAllByConditions( null, Book.class);
  69. for (Book book : books) {
  70. System.out.println(book);
  71. }
  72. }
  73. }
7、测试结果

说明:该代码是早期的版本,功能比较简单,代码写得也比较笨拙,还有待优化,但是思路是非常好的,日后采用Spring进行改造,另外注解可以直接采用javax.persistence.*里的,不用自己再写了,否则容易产生歧义。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值