经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
Mybatis总结之如何自动生成数据库表结构
来源:cnblogs  作者:Dream Young  时间:2019/11/1 14:18:47  对本文有异议

一般情况下,用Mybatis的时候是先设计表结构再进行实体类以及映射文件编写的,特别是用代码生成器的时候。

但有时候不想用代码生成器,也不想定义表结构,那怎么办?

这个时候就会想到Hibernate,然后想到它的hibernate.hbm2ddl.auto配置项。

所以手工创表的问题可以很方便的迅速用Hibernate来解决。 那有人问啦:有就是不想用Hibernate才换的Mybatis,你这又兜回去了吗?

其实不是的,我们需要的就是单单一个hbm2ddl功能。

其实应该这么想:有一款工具能够自动根据注解的实体类来生成各种数据库相应的表结构,只需要加几个jar包  (经测试后只要7个)并且 少量配置(3个配置项) 

这款工具就是Hibernate。为什么不能是它呢!!!

原理说来也是超级的简单:   加入hibernate的包,程序开始时初始化一下hibernate的SessionFactory并清除它。

示例:

需要的Hibernate相关的JAR包 (本例基于Hibernate5.0.7,仅需要7个):

          hibernate-core-5.0.7.Final.jar

          hibernate-commons-annotations-5.0.1.Final.jar

          hibernate-jpa-2.1-api-1.0.0.Final.jar

          geronimo-jta_1.1_spec-1.1.1.jar

          jboss-logging-3.3.0.Final.jar

          dom4j-1.6.1.jar

          javassist-3.18.1-GA.jar

Hibernate.cfg.xml文件:(去掉多余的,精简后的内容)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <!--不采用InnoDB方式加快速度 -->
  8. <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
  9.  
  10. <!-- 注意update方式时对于属性的删减并不会删除数据库字段 -->
  11. <property name="hibernate.hbm2ddl.auto">update</property>
  12.  
  13. <!-- 注意注解的话,只能用class一个一个引用。除非与Spring整合才能扫描文件夹路径 -->
  14. <mapping class="com.sunwii.mybatis.bean.User" />
  15. </session-factory>
  16. </hibernate-configuration>

其它东西不需要,只需要在使用SqlSessionFactory(Mybatis)之前就构造SessionFactory(Hibernate)然后销毁它就可以了。

与Spring整合时:按照正常的Hibernate与Spring整合的方案就可以。

不与Spring整合时:Mybatis的工具类中添加新方法,用于自动构造DDL:

  1. package com.sunwii.mybatis.util;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSessionFactory;
  6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  7. import com.sunwii.mybatis.constant.Constants;
  8. public class SessionFactoryUtil {
  9. public static SqlSessionFactory creat(String configFile) {
  10. SqlSessionFactory factory = null;
  11. InputStream inputStream;
  12. try {
  13. inputStream = Resources.getResourceAsStream(configFile);
  14. factory = new SqlSessionFactoryBuilder().build(inputStream);
  15. } catch (IOException e) {
  16. // TODO Auto-generated catch block
  17. e.printStackTrace();
  18. }
  19. return factory;
  20. }

  21. //这里是新方法,通过判断标记决定是否要用于自动生成DDL
  22. public static SqlSessionFactory creat(String configFile, boolean hibernateAutoDdl) {
  23. if (hibernateAutoDdl) {
  24. String hibernateConfigFile = Constants.Hibernate_LOCATION;
  25. // 使用hibernate自动创建DDL
  26. HibernateUtil.buildSessionFactory(hibernateConfigFile);
  27. }
  28. return creat(configFile);
  29. }
  30. }

其中用到的Hibernate工具类为:

  1. package com.sunwii.mybatis.util;
  2. import java.util.Properties;
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5. import com.sunwii.mybatis.constant.Constants;
  6. public class HibernateUtil {
  7. public static void buildSessionFactory(String hibernateConfigFile) {
  8. String jdbcPropertiesLocation = Constants.JDBC_LOCATION;
  9. Properties jdbcProperties = PropertiesUtil.loadFromClassPath(jdbcPropertiesLocation);
  10. Properties hibernateJdbcProperties = new Properties();
  11. hibernateJdbcProperties.setProperty("hibernate.connection.driver_class", jdbcProperties.getProperty("driver"));
  12. hibernateJdbcProperties.setProperty("hibernate.connection.url", jdbcProperties.getProperty("url"));
  13. hibernateJdbcProperties.setProperty("hibernate.connection.username", jdbcProperties.getProperty("user"));
  14. hibernateJdbcProperties.setProperty("hibernate.connection.password", jdbcProperties.getProperty("password"));
  15. final Configuration cfg = new Configuration();
  16. cfg.addProperties(hibernateJdbcProperties);
  17. cfg.configure(hibernateConfigFile);
  18. SessionFactory sessionFactory = cfg.buildSessionFactory();
  19. // 启动后销毁
  20. sessionFactory.close();
  21. sessionFactory = null;
  22. }
  23. }

PropertiesUtil工具类

  1. package com.sunwii.mybatis.util;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.Properties;
  5. public class PropertiesUtil {
  6. public static Properties loadFromClassPath(String fileName) {
  7. Properties props = new Properties();
  8. while(fileName!=null && fileName.length()>0 && (fileName.startsWith("/") || fileName.startsWith("\\"))) {
  9. fileName = fileName.substring(1);
  10. }
  11. InputStream is = Class.class.getResourceAsStream("/"+fileName);
  12. try {
  13. props.load(is);
  14. } catch (IOException e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. return props;
  19. }
  20. }

常量配置类Constant:

  1. package com.sunwii.mybatis.constant;
  2. public class Constants {
  3. public static String JDBC_LOCATION = "jdbc.properties";
  4. public static String Hibernate_LOCATION = "hibernate.cfg.xml";
  5. }

示例的实体类User

  1. @Entity
  2. @Table(name = "t_user")
  3. @Data
  4. @NoArgsConstructor
  5. @ToString
  6. public class User implements Serializable {
  7. private static final long serialVersionUID = -4013951528313410972L;
  8. @Id
  9. @GeneratedValue(strategy = GenerationType.IDENTITY)
  10. @Column(name = "id")
  11. private Integer id;
  12. @Column(length = 30)
  13. private String name;
  14. @Column
  15. private Float height;
  16. @Column
  17. private Double salary;
  18. @Column
  19. private Integer vip;
  20. @Column
  21. @Temporal(TemporalType.DATE)
  22. private Date birthday;
  23. @Column
  24. @Temporal(TemporalType.TIMESTAMP)
  25. private Date lastlogin;
  26. @Column
  27. @Enumerated(EnumType.STRING)
  28. // mybatis 默认会将枚举转化为字符串类型存储,此时数据库为varchar型
  29. private State state;
  30. @Column
  31. @Enumerated(EnumType.ORDINAL)
  32. // 可以为mybatis设置枚举类型存储为其索引值存储,此时数据库为int型
  33. private Level level;
  34. @Column(length = 10)
  35. @Enumerated(EnumType.ORDINAL)
  36. // mybatis 自定义类型转换器将枚举转化为相应数字类型存储,此时数据库为int型
  37. private Sex sex;
  38. @Column
  39. @Type(type = "string")
  40. // mybatis 自定义类型转换器将列表转化为相应字符串类型存储,此时数据库为varchar型
  41. private List<String> tels;
  42. public User(int id) {
  43. super();
  44. this.id = id;
  45. }
  46. public User(int id, String name) {
  47. super();
  48. this.id = id;
  49. this.name = name;
  50. }
  51. public User(String name) {
  52. super();
  53. this.name = name;
  54. }
  55. }

注意:以上实体类用于Lombok插件,

  1. @Data
  2. @NoArgsConstructor
  3. @ToString
    三个注解属于Lombok插件注解,分别指示生成SETTER/GETTER生成无参构造器生成ToString
    其它注解都属于HibernateJPA规范)的注解,生成DDL就靠它们了。

Mybatis配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!-- 别名 -->
  7. <typeAliases>
  8. <!-- 指定包下所有别名为类名的简名 -->
  9. <package name="com.sunwii.mybatis.bean" />
  10. </typeAliases>
  11.  
  12. <!-- 类型处理器 -->
  13. <typeHandlers>
  14. <!-- 改变默认处理枚举(枚举转换为int) -->
  15. <typeHandler
  16. handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
  17. javaType="com.sunwii.mybatis.enums.Level" />
  18.  
  19. <!-- 自定义处理枚举(枚举转换为枚举键值对的数字值) -->
  20. <typeHandler
  21. handler="com.sunwii.mybatis.typehandle.SexEnumTypeHandler"
  22. javaType="com.sunwii.mybatis.enums.Sex" />
  23.  
  24. <!-- 自定义处理列表(列表转换为字符串连接) -->
  25. <!-- 注意,由于是非内置的转换类型,所以仅对select有效,insert/update/delete需要另行指定 -->
  26. <!-- 另行指定示例:${tels,typeHandler=com.sunwii.mybatis.typehandle.ListTypeHandler} -->
  27. <typeHandler
  28. handler="com.sunwii.mybatis.typehandle.ListTypeHandler"
  29. javaType="java.util.List" />
  30. </typeHandlers>
  31.  
  32.  
  33. <environments default="development">
  34. <environment id="development">
  35. <transactionManager type="JDBC" />
  36. <!-- 自定义MyPoolDataSourceFactory简化配置 -->
  37. <dataSource type="com.sunwii.mybatis.pool.MyPoolDataSourceFactory" />
  38. </environment>
  39. </environments>
  40.  
  41. <mappers>
  42. <package name="com/sunwii/mybatis/mapper" />
  43. </mappers>
  44. </configuration>

连接池装饰类(用于简化Mybatis配置并统一jdbc配置文件路径常量):

  1. package com.sunwii.mybatis.pool;
  2. import java.util.Properties;
  3. import org.apache.ibatis.datasource.pooled.PooledDataSource;
  4. import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
  5. import com.sunwii.mybatis.constant.Constants;
  6. import com.sunwii.mybatis.util.PropertiesUtil;
  7. public class MyPoolDataSourceFactory extends PooledDataSourceFactory {
  8. public MyPoolDataSourceFactory() {
  9. PooledDataSource dataSource = new PooledDataSource();
  10. // 更多属性可以通过<property>来设置。
  11. String jdbcPropertiesFile = Constants.JDBC_LOCATION;
  12. Properties prop = PropertiesUtil.loadFromClassPath(jdbcPropertiesFile);
  13. dataSource.setDriver(prop.getProperty("driver"));
  14. dataSource.setUrl(prop.getProperty("url"));
  15. dataSource.setUsername(prop.getProperty("user"));
  16. dataSource.setPassword(prop.getProperty("password"));
  17. this.dataSource = dataSource;
  18. }
  19. }

用到的几个枚举类:

  1. package com.sunwii.mybatis.enums;
  2. public enum Level {
  3. LEVEL_0,
  4. LEVEL_1,
  5. LEVEL_2,
  6. LEVEL_3,
  7. LEVEL_4,
  8. LEVEL_5
  9. }
  10. package com.sunwii.mybatis.enums;
  11. import java.util.HashMap;
  12. public enum Sex {
  13. MAN("男", 0), WOMAN("女", 1);
  14. private String key;
  15. public String getKey() {
  16. return key;
  17. }
  18. public void setKey(String key) {
  19. this.key = key;
  20. }
  21. public Integer getValue() {
  22. return value;
  23. }
  24. public void setValue(Integer value) {
  25. this.value = value;
  26. }
  27. private Integer value;
  28. private static HashMap<Integer, Sex> valueMap = new HashMap<Integer, Sex>();
  29. private static HashMap<String, Sex> keyMap = new HashMap<String, Sex>();
  30. static {
  31. for (Sex item : Sex.values()) {
  32. valueMap.put(item.value, item);
  33. keyMap.put(item.key, item);
  34. }
  35. }
  36. Sex(String key, Integer value) {
  37. this.key = key;
  38. this.value = value;
  39. }
  40. public static Sex getByValue(int value) {
  41. Sex result = valueMap.get(value);
  42. return result;
  43. }
  44. public static Sex getByKey(String key) {
  45. Sex result = keyMap.get(key);
  46. return result;
  47. }
  48. }
  49. package com.sunwii.mybatis.enums;
  50. public enum State {
  51. OK, ERROR, UNKNOWN
  52. }

用到的类型转换器:

  1. package com.sunwii.mybatis.typehandle;
  2. import java.sql.CallableStatement;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import org.apache.ibatis.type.JdbcType;
  7. import org.apache.ibatis.type.TypeHandler;
  8. import com.sunwii.mybatis.enums.Sex;
  9. /**
  10. * -必须实现所有方法,不然的话查询有可能查询到为null
  11. * @author Administrator
  12. *
  13. */
  14. public class SexEnumTypeHandler implements TypeHandler<Sex> {
  15. /**
  16. * 转换到数据库的值
  17. */
  18. @Override
  19. public void setParameter(PreparedStatement ps, int i, Sex parameter, JdbcType jdbcType) throws SQLException {
  20. ps.setInt(i, parameter.getValue());
  21. }
  22. /**
  23. * 从数据库转换得到
  24. */
  25. @Override
  26. public Sex getResult(ResultSet rs, String columnName) throws SQLException {
  27. return Sex.getByValue(rs.getInt(columnName));
  28. }
  29. /**
  30. * 从数据库转换得到
  31. */
  32. @Override
  33. public Sex getResult(ResultSet rs, int columnIndex) throws SQLException {
  34. return Sex.getByValue(rs.getInt(columnIndex));
  35. }
  36. /**
  37. * 从数据库转换得到
  38. */
  39. @Override
  40. public Sex getResult(CallableStatement cs, int columnIndex) throws SQLException {
  41. return Sex.getByValue(cs.getInt(columnIndex));
  42. }
  43. }
  1. package com.sunwii.mybatis.typehandle;
  2. import java.sql.CallableStatement;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.Arrays;
  7. import java.util.List;
  8. import org.apache.ibatis.type.JdbcType;
  9. import org.apache.ibatis.type.TypeHandler;
  10. import com.sunwii.mybatis.util.ArrayUtil;
  11. /**
  12. * -必须实现所有方法,不然的话查询有可能查询到为null
  13. * @author Administrator
  14. *
  15. */
  16. public class ListTypeHandler implements TypeHandler<List<?>> {
  17. @SuppressWarnings({ "unchecked", "rawtypes" })
  18. @Override
  19. public void setParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException {
  20. String[] strArr = ArrayUtil.fromList((List<String>) parameter);
  21. String strs = ArrayUtil.asString(",", strArr);
  22. ps.setString(i, strs);
  23. }
  24. @Override
  25. public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
  26. List<String> list = null;
  27. String strs = rs.getString(columnName);
  28. if (strs != null && strs.length() > 0) {
  29. list = Arrays.asList(strs.split(","));
  30. }
  31. return list;
  32. }
  33. @Override
  34. public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
  35. List<String> list = null;
  36. String strs = rs.getString(columnIndex);
  37. if (strs != null && strs.length() > 0) {
  38. list = Arrays.asList(strs.split(","));
  39. }
  40. return list;
  41. }
  42. @Override
  43. public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
  44. List<String> list = null;
  45. String strs = cs.getString(columnIndex);
  46. if (strs != null && strs.length() > 0) {
  47. list = Arrays.asList(strs.split(","));
  48. }
  49. return list;
  50. }
  51. }

用到的数组集合转换工具类

  1. package com.sunwii.mybatis.util;
  2. import java.lang.reflect.Array;
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collection;
  6. import java.util.HashMap;
  7. import java.util.HashSet;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Set;
  11. public class ArrayUtil {
  12. @SuppressWarnings("unchecked")
  13. public static <T> List<T> asList(T... args) {
  14. return Arrays.asList(args);
  15. }
  16. public static <T> List<T> asListFromSet(Set<T> set) {
  17. if (set == null || set.size() < 1) {
  18. return null;
  19. }
  20. List<T> list = new ArrayList<T>();
  21. for (T t : set) {
  22. list.add(t);
  23. }
  24. return list;
  25. }
  26. public static <T> List<T> asListFromArray(T[] array) {
  27. if (array == null || array.length < 1) {
  28. return null;
  29. }
  30. List<T> list = new ArrayList<T>();
  31. for (T t : array) {
  32. list.add(t);
  33. }
  34. return list;
  35. }
  36. public static <T> List<T> asListFromMapKey(Map<T, ?> map) {
  37. if (map == null || map.size() < 1) {
  38. return null;
  39. }
  40. return ArrayUtil.asListFromSet(map.keySet());
  41. }
  42. public static <T> List<T> asListFromMapValue(Map<?, T> map) {
  43. if (map == null || map.size() < 1) {
  44. return null;
  45. }
  46. List<T> list = new ArrayList<T>();
  47. Collection<T> values = map.values();
  48. for (T t : values) {
  49. list.add(t);
  50. }
  51. return list;
  52. }
  53. @SuppressWarnings("unchecked")
  54. public static <T> T[] fromArray(T... args) {
  55. if (args == null || args.length < 1) {
  56. return null;
  57. }
  58. T[] array = (T[]) Array.newInstance(args[0].getClass(), args.length);
  59. for (int i = 0; i < args.length; i++) {
  60. array[i] = args[i];
  61. }
  62. return array;
  63. }
  64. @SuppressWarnings("unchecked")
  65. public static <T> T[] fromList(List<T> list) {
  66. if (list == null || list.size() < 1) {
  67. return null;
  68. }
  69. Class<T> clz = null;
  70. for (T t : list) {
  71. clz = (Class<T>) t.getClass();
  72. break;
  73. }
  74. T[] array = (T[]) Array.newInstance(clz, list.size());
  75. int i = 0;
  76. for (T t : list) {
  77. array[i] = t;
  78. i++;
  79. }
  80. return array;
  81. }
  82. @SuppressWarnings("unchecked")
  83. public static <T> T[] fromSet(Set<T> set) {
  84. if (set == null || set.size() < 1) {
  85. return null;
  86. }
  87. Class<T> clz = null;
  88. for (T t : set) {
  89. clz = (Class<T>) t.getClass();
  90. break;
  91. }
  92. T[] array = (T[]) Array.newInstance(clz, set.size());
  93. int i = 0;
  94. for (T t : set) {
  95. array[i] = t;
  96. i++;
  97. }
  98. return array;
  99. }
  100. public static <T> T[] fromMapKey(Map<T, ?> map) {
  101. if (map == null || map.size() < 1) {
  102. return null;
  103. }
  104. Set<T> set = map.keySet();
  105. return ArrayUtil.fromSet(set);
  106. }
  107. public static <T> T[] fromMapValue(Map<?, T> map) {
  108. if (map == null || map.size() < 1) {
  109. return null;
  110. }
  111. List<T> list = new ArrayList<T>();
  112. Collection<T> values = map.values();
  113. for (T t : values) {
  114. list.add(t);
  115. }
  116. return ArrayUtil.fromList(list);
  117. }
  118. @SuppressWarnings("unchecked")
  119. public static <T> Set<T> asSet(T... args) {
  120. if (args == null || args.length < 1) {
  121. return null;
  122. }
  123. Set<T> set = new HashSet<T>();
  124. for (int i = 0; i < args.length; i++) {
  125. if (!set.contains(args[i])) {
  126. set.add(args[i]);
  127. }
  128. }
  129. return set;
  130. }
  131. public static <T> Set<T> asSetFromArray(T[] array) {
  132. if (array == null || array.length < 1) {
  133. return null;
  134. }
  135. Set<T> set = new HashSet<T>();
  136. for (T t : array) {
  137. set.add(t);
  138. }
  139. return set;
  140. }
  141. public static <T> Set<T> asSetFromMapKey(Map<T, ?> map) {
  142. if (map == null || map.size() < 1) {
  143. return null;
  144. }
  145. return map.keySet();
  146. }
  147. public static <T> Set<T> asSetFromMapValue(Map<?, T> map) {
  148. if (map == null || map.size() < 1) {
  149. return null;
  150. }
  151. Set<T> set = new HashSet<T>();
  152. Collection<T> values = map.values();
  153. for (T t : values) {
  154. set.add(t);
  155. }
  156. return set;
  157. }
  158. public static <T1, T2> Map<T1, T2> asMapFrom(Set<T1> keySet, Set<T2> valueSet) {
  159. if (keySet == null || keySet.size() < 1 || valueSet == null || valueSet.size() < 1) {
  160. return null;
  161. }
  162. Map<T1, T2> map = new HashMap<T1, T2>();
  163. List<T2> list = ArrayUtil.asListFromSet(valueSet);
  164. int i = 0;
  165. for (T1 t : keySet) {
  166. try {
  167. map.put(t, list.get(i++));
  168. } catch (Exception e) {// 超长
  169. map.put(t, null);
  170. }
  171. }
  172. return map;
  173. }
  174. @SuppressWarnings("unchecked")
  175. public static <T> String asString(String separator, T... args) {
  176. if (args == null || args.length < 1) {
  177. return null;
  178. }
  179. StringBuilder sp = new StringBuilder();
  180. for (int i = 0; i < args.length; i++) {
  181. sp.append(args[i]);
  182. if (i != args.length - 1) {
  183. sp.append(separator);
  184. }
  185. }
  186. return sp.toString();
  187. }
  188. }

映射文件:UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.sunwii.mybatis.mapper.UserMapper">
  6. <select id="selectById" parameterType="Integer"
  7. resultType="User">
  8. select * from t_user where id = #{id}
  9. </select>
  10.  
  11. <select id="selectByName" parameterType="String"
  12. resultType="User">
  13. select * from t_user where name like "%"#{name}"%"
  14. </select>
  15.  
  16. <insert id="insert">
  17. insert into
  18. t_user(
  19. name, birthday, vip, salary, height, lastlogin,level,state,sex,tels
  20. )values(
  21. #{name},
  22. #{birthday},
  23. #{vip},
  24. #{salary},
  25. #{height},
  26. #{lastlogin},
  27. #{level},
  28. #{state},
  29. #{sex},
  30. #{tels,typeHandler=com.sunwii.mybatis.typehandle.ListTypeHandler}
  31. )
  32. </insert>
  33.  
  34. <update id="update">
  35. update t_user set
  36. name=#{name},
  37. birthday=#{birthday},
  38. vip=#{vip},
  39. salary=#{salary},
  40. height=#{height},
  41. lastlogin=#{lastlogin},
  42. level=#{level},
  43. state=#{state},
  44. sex=#{sex},
  45. tels=#{tels,typeHandler=com.sunwii.mybatis.typehandle.ListTypeHandler}
  46. where id=#{id}
  47. </update>
  48.  
  49. <delete id="delete" parameterType="Integer">
  50. delete from t_user where
  51. id=#{id}
  52. </delete>
  53. </mapper>

测试示例:

  1. package com.sunwii.mybatis.test.mapper;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import org.apache.commons.logging.Log;
  5. import org.apache.commons.logging.LogFactory;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactory;
  8. import org.junit.Test;
  9. import com.sunwii.mybatis.bean.User;
  10. import com.sunwii.mybatis.enums.Level;
  11. import com.sunwii.mybatis.enums.Sex;
  12. import com.sunwii.mybatis.enums.State;
  13. import com.sunwii.mybatis.mapper.UserMapper;
  14. import com.sunwii.mybatis.test.insert.TestInsert;
  15. import com.sunwii.mybatis.util.CurrentUtil;
  16. import com.sunwii.mybatis.util.SessionFactoryUtil;
  17. public class testMapper {
  18. private static Log log = LogFactory.getLog(TestInsert.class);
  19. private static SqlSessionFactory sf = SessionFactoryUtil.creat("mybatis-config.xml", true);
  20. @Test
  21. public void testMapperInsert() {
  22. User user = new User();
  23. //user.setId(50);
  24. user.setName("sunwii");
  25. user.setVip(1);
  26. user.setSalary(3333.00);
  27. user.setHeight(1.70f);
  28. user.setBirthday(CurrentUtil.currentDate());
  29. user.setLastlogin(CurrentUtil.currentTimestamp());
  30. user.setLevel(Level.LEVEL_3);
  31. user.setState(State.OK);
  32. user.setSex(Sex.WOMAN);
  33. user.setTels(Arrays.asList("133xxxxxxx", "159xxxxxxxx"));
  34. int rs = 0;
  35. SqlSession session = sf.openSession();
  36. UserMapper userMapper = session.getMapper(UserMapper.class);
  37. try {
  38. rs = userMapper.insert(user);
  39. session.commit();
  40. } catch (Exception e) {
  41. rs = 0;
  42. session.rollback();
  43. e.printStackTrace();
  44. } finally {
  45. session.close();
  46. }
  47. log.info("操作结果:" + rs);
  48. }
  49. @Test
  50. public void testMapperUpdate() {
  51. User user = new User();
  52. user.setId(1);
  53. user.setName("sunwii--55550");
  54. user.setVip(1);
  55. user.setSalary(3333.00);
  56. user.setHeight(1.70f);
  57. user.setBirthday(CurrentUtil.currentDate());
  58. user.setLastlogin(CurrentUtil.currentTimestamp());
  59. user.setLevel(Level.LEVEL_2);
  60. user.setState(State.ERROR);
  61. user.setSex(Sex.MAN);
  62. user.setTels(Arrays.asList("136xxxxxx", "139xxxxxxx"));
  63. int rs = 0;
  64. SqlSession session = sf.openSession();
  65. UserMapper userMapper = session.getMapper(UserMapper.class);
  66. try {
  67. rs = userMapper.update(user);
  68. session.commit();
  69. } catch (Exception e) {
  70. rs = 0;
  71. session.rollback();
  72. e.printStackTrace();
  73. } finally {
  74. session.close();
  75. }
  76. log.info("操作结果:" + rs);
  77. }
  78. @Test
  79. public void testMapperDelete() {
  80. User user = new User(50);
  81. int rs = 0;
  82. SqlSession session = sf.openSession();
  83. UserMapper userMapper = session.getMapper(UserMapper.class);
  84. try {
  85. rs = userMapper.delete(user.getId());
  86. session.commit();
  87. } catch (Exception e) {
  88. rs = 0;
  89. session.rollback();
  90. e.printStackTrace();
  91. } finally {
  92. session.close();
  93. }
  94. log.info("操作结果:" + rs);
  95. }
  96. @Test
  97. public void testMapperGetOne() {
  98. Integer id = 50;
  99. User user = null;
  100. SqlSession session = sf.openSession();
  101. UserMapper userMapper = session.getMapper(UserMapper.class);
  102. user = userMapper.selectById(id);
  103. log.info(user);
  104. }
  105. @Test
  106. public void testMapperGetList() {
  107. String userName = "sunwii";
  108. List<User> users = null;
  109. SqlSession session = sf.openSession();
  110. UserMapper userMapper = session.getMapper(UserMapper.class);
  111. users = userMapper.selectByName(userName);
  112. for (User user : users) {
  113. log.info(user);
  114. }
  115. }
  116. }

<<Mybatis总结之如何自动生成数据库表结构>>

说明: 

    这里多余的步骤仅仅是为了存档下代码(以及方便一些初学者不看代码不知道怎么回事的原因:里边涉及了各种常用类型的转换和映射)。

    本文中最重要的就是Hibernate的几个包的选取,以及配置文件的精简,还有就是加载Hibernate的SessionFactory的方法。

    这些说来说去都是Hibernate的东西。跟Mybatis原本是没有一点关系的。只不过需要用于,那纯属相当于复习一下Hibernate了。

原文链接:http://www.cnblogs.com/dreamyoung/p/11776426.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号