Mybatis如何自動生成數(shù)據(jù)庫表結(jié)構(gòu)總結(jié)
一般情況下,用Mybatis的時(shí)候是先設(shè)計(jì)表結(jié)構(gòu)再進(jìn)行實(shí)體類以及映射文件編寫的,特別是用代碼生成器的時(shí)候。
但有時(shí)候不想用代碼生成器,也不想定義表結(jié)構(gòu),那怎么辦?
這個時(shí)候就會想到Hibernate,然后想到它的hibernate.hbm2ddl.auto配置項(xiàng)。
所以手工創(chuàng)表的問題可以很方便的迅速用Hibernate來解決。 那有人問啦:就是不想用Hibernate才換的Mybatis,你這又兜回去了嗎?
其實(shí)不是的,我們需要的就是單單一個hbm2ddl功能。
其實(shí)應(yīng)該這么想:有一款工具能夠自動根據(jù)注解的實(shí)體類來生成各種數(shù)據(jù)庫相應(yīng)的表結(jié)構(gòu),只需要加幾個jar包 (經(jīng)測試后只要7個)并且 少量配置(3個配置項(xiàng)) 。
這款工具就是Hibernate。為什么不能是它呢?。?!
原理說來也是超級的簡單: 加入hibernate的包, 注解實(shí)體類,程序開始時(shí)初始化一下hibernate的SessionFactory并清除它。
示例:
需要的Hibernate相關(guān)的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文件:(去掉多余的,精簡后的內(nèi)容)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!--不采用InnoDB方式加快速度 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 注意update方式時(shí)對于屬性的刪減并不會刪除數(shù)據(jù)庫字段 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 注意注解的話,只能用class一個一個引用。除非與Spring整合才能掃描文件夾路徑 --> <mapping class="com.sunwii.mybatis.bean.User" /> </session-factory> </hibernate-configuration>
注解的實(shí)體類:
@Entity
@Table(name = "t_user")
@Data
@NoArgsConstructor
@ToString
public class User implements Serializable {
private static final long serialVersionUID = -4013951528313410972L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(length = 30)
private String name;
@Column
private Float height;
@Column
private Double salary;
@Column
private Integer vip;
@Column
@Temporal(TemporalType.DATE)
private Date birthday;
@Column
@Temporal(TemporalType.TIMESTAMP)
private Date lastlogin;
@Column
@Enumerated(EnumType.STRING)
// mybatis 默認(rèn)會將枚舉轉(zhuǎn)化為字符串類型存儲,此時(shí)數(shù)據(jù)庫為varchar型
private State state;
@Column
@Enumerated(EnumType.ORDINAL)
// 可以為mybatis設(shè)置枚舉類型存儲為其索引值存儲,此時(shí)數(shù)據(jù)庫為int型
private Level level;
@Column(length = 10)
@Enumerated(EnumType.ORDINAL)
// mybatis 自定義類型轉(zhuǎn)換器將枚舉轉(zhuǎn)化為相應(yīng)數(shù)字類型存儲,此時(shí)數(shù)據(jù)庫為int型
private Sex sex;
@Column
@Type(type = "string")
// mybatis 自定義類型轉(zhuǎn)換器將列表轉(zhuǎn)化為相應(yīng)字符串類型存儲,此時(shí)數(shù)據(jù)庫為varchar型
private List<String> tels;
public User(int id) {
super();
this.id = id;
}
public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public User(String name) {
super();
this.name = name;
}
}
注意:以上實(shí)體類用了Lombok插件來減少代碼量(只要是為了不寫setter/getter、toString等。Lombok插件的使用請參考其它地方。)
@Data
@NoArgsConstructor
@ToString
三個注解屬于Lombok插件注解,分別指示生成SETTER/GETTER、生成無參構(gòu)造器、生成ToString
其它注解都屬于Hibernate(JPA規(guī)范)的注解,生成DDL就靠它們了。
注解-說明:
@Entity @Table(name = "t_user") 這里指實(shí)體類對應(yīng)了t_user表 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") 這里指表主健自動增長 @Column 這里指表字段名稱與屬性同名,它可以另外指定長度,名稱。 @Temporal(TemporalType.DATE) 這里指表字段采用Date類型存儲 @Enumerated(EnumType.STRING) 這里指表字段采用varchar類型來存儲枚舉屬性 這個簡短示例僅列出簡單的類型的注解,并不涉及表關(guān)聯(lián)之間的注解,幸好的是,注解并不多,更多注解可以參考Hibernate(JPA)注解相關(guān)內(nèi)容。
至此,只需要在使用SqlSessionFactory(Mybatis)之前就構(gòu)造SessionFactory(Hibernate)然后銷毀它就可以了。至于如何初始化Hibernate的SessionFactory,應(yīng)該都知道。如下:
Mybatis與Spring整合時(shí):簡單地配置一個hibernate的SessionFactory相關(guān)的BEAN了事。這里不談。
Mybatis不與Spring整合時(shí):
Mybatis的工具類中添加新方法,用于自動構(gòu)造DDL:
package com.sunwii.mybatis.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.sunwii.mybatis.constant.Constants;
public class SessionFactoryUtil {
public static SqlSessionFactory creat(String configFile) {
SqlSessionFactory factory = null;
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(configFile);
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return factory;
}
//這里是新方法,通過判斷標(biāo)記決定是否要用于自動生成DDL
public static SqlSessionFactory creat(String configFile, boolean hibernateAutoDdl) {
if (hibernateAutoDdl) {
String hibernateConfigFile = Constants.Hibernate_LOCATION;
// 使用hibernate自動創(chuàng)建DDL
HibernateUtil.buildSessionFactory(hibernateConfigFile);
}
return creat(configFile);
}
}
其中用到的Hibernate工具類為:
package com.sunwii.mybatis.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.sunwii.mybatis.constant.Constants;
public class HibernateUtil {
public static void buildSessionFactory(String hibernateConfigFile) {
String jdbcPropertiesLocation = Constants.JDBC_LOCATION;
Properties jdbcProperties = PropertiesUtil.loadFromClassPath(jdbcPropertiesLocation);
Properties hibernateJdbcProperties = new Properties();
hibernateJdbcProperties.setProperty("hibernate.connection.driver_class", jdbcProperties.getProperty("driver"));
hibernateJdbcProperties.setProperty("hibernate.connection.url", jdbcProperties.getProperty("url"));
hibernateJdbcProperties.setProperty("hibernate.connection.username", jdbcProperties.getProperty("user"));
hibernateJdbcProperties.setProperty("hibernate.connection.password", jdbcProperties.getProperty("password"));
final Configuration cfg = new Configuration();
cfg.addProperties(hibernateJdbcProperties);
cfg.configure(hibernateConfigFile);
SessionFactory sessionFactory = cfg.buildSessionFactory();
// 啟動后銷毀
sessionFactory.close();
sessionFactory = null;
}
}
PropertiesUtil工具類:
package com.sunwii.mybatis.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
public static Properties loadFromClassPath(String fileName) {
Properties props = new Properties();
while(fileName!=null && fileName.length()>0 && (fileName.startsWith("/") || fileName.startsWith("\\"))) {
fileName = fileName.substring(1);
}
InputStream is = Class.class.getResourceAsStream("/"+fileName);
try {
props.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return props;
}
}
常量配置類Constant:
package com.sunwii.mybatis.constant;
public class Constants {
public static String JDBC_LOCATION = "jdbc.properties";
public static String Hibernate_LOCATION = "hibernate.cfg.xml";
}
Mybatis配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 別名 -->
<typeAliases>
<!-- 指定包下所有別名為類名的簡名 -->
<package name="com.sunwii.mybatis.bean" />
</typeAliases>
<!-- 類型處理器 -->
<typeHandlers>
<!-- 改變默認(rèn)處理枚舉(枚舉轉(zhuǎn)換為int) -->
<typeHandler
handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
javaType="com.sunwii.mybatis.enums.Level" />
<!-- 自定義處理枚舉(枚舉轉(zhuǎn)換為枚舉鍵值對的數(shù)字值) -->
<typeHandler
handler="com.sunwii.mybatis.typehandle.SexEnumTypeHandler"
javaType="com.sunwii.mybatis.enums.Sex" />
<!-- 自定義處理列表(列表轉(zhuǎn)換為字符串連接) -->
<!-- 注意,由于是非內(nèi)置的轉(zhuǎn)換類型,所以僅對select有效,insert/update/delete需要另行指定 -->
<!-- 另行指定示例:${tels,typeHandler=com.sunwii.mybatis.typehandle.ListTypeHandler} -->
<typeHandler
handler="com.sunwii.mybatis.typehandle.ListTypeHandler"
javaType="java.util.List" />
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 自定義MyPoolDataSourceFactory簡化配置 -->
<dataSource type="com.sunwii.mybatis.pool.MyPoolDataSourceFactory" />
</environment>
</environments>
<mappers>
<package name="com/sunwii/mybatis/mapper" />
</mappers>
</configuration>
連接池裝飾類(用于簡化Mybatis配置并統(tǒng)一jdbc配置文件路徑常量):
package com.sunwii.mybatis.pool;
import java.util.Properties;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import com.sunwii.mybatis.constant.Constants;
import com.sunwii.mybatis.util.PropertiesUtil;
public class MyPoolDataSourceFactory extends PooledDataSourceFactory {
public MyPoolDataSourceFactory() {
PooledDataSource dataSource = new PooledDataSource();
// 更多屬性可以通過<property>來設(shè)置。
String jdbcPropertiesFile = Constants.JDBC_LOCATION;
Properties prop = PropertiesUtil.loadFromClassPath(jdbcPropertiesFile);
dataSource.setDriver(prop.getProperty("driver"));
dataSource.setUrl(prop.getProperty("url"));
dataSource.setUsername(prop.getProperty("user"));
dataSource.setPassword(prop.getProperty("password"));
this.dataSource = dataSource;
}
}
用到的幾個枚舉類:
package com.sunwii.mybatis.enums;
public enum Level {
LEVEL_0,
LEVEL_1,
LEVEL_2,
LEVEL_3,
LEVEL_4,
LEVEL_5
}
package com.sunwii.mybatis.enums;
import java.util.HashMap;
public enum Sex {
MAN("男", 0), WOMAN("女", 1);
private String key;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
private Integer value;
private static HashMap<Integer, Sex> valueMap = new HashMap<Integer, Sex>();
private static HashMap<String, Sex> keyMap = new HashMap<String, Sex>();
static {
for (Sex item : Sex.values()) {
valueMap.put(item.value, item);
keyMap.put(item.key, item);
}
}
Sex(String key, Integer value) {
this.key = key;
this.value = value;
}
public static Sex getByValue(int value) {
Sex result = valueMap.get(value);
return result;
}
public static Sex getByKey(String key) {
Sex result = keyMap.get(key);
return result;
}
}
package com.sunwii.mybatis.enums;
public enum State {
OK, ERROR, UNKNOWN
}
用到的類型轉(zhuǎn)換器:
package com.sunwii.mybatis.typehandle;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import com.sunwii.mybatis.enums.Sex;
/**
* -必須實(shí)現(xiàn)所有方法,不然的話查詢有可能查詢到為null
* @author Administrator
*
*/
public class SexEnumTypeHandler implements TypeHandler<Sex> {
/**
* 轉(zhuǎn)換到數(shù)據(jù)庫的值
*/
@Override
public void setParameter(PreparedStatement ps, int i, Sex parameter, JdbcType jdbcType) throws SQLException {
ps.setInt(i, parameter.getValue());
}
/**
* 從數(shù)據(jù)庫轉(zhuǎn)換得到
*/
@Override
public Sex getResult(ResultSet rs, String columnName) throws SQLException {
return Sex.getByValue(rs.getInt(columnName));
}
/**
* 從數(shù)據(jù)庫轉(zhuǎn)換得到
*/
@Override
public Sex getResult(ResultSet rs, int columnIndex) throws SQLException {
return Sex.getByValue(rs.getInt(columnIndex));
}
/**
* 從數(shù)據(jù)庫轉(zhuǎn)換得到
*/
@Override
public Sex getResult(CallableStatement cs, int columnIndex) throws SQLException {
return Sex.getByValue(cs.getInt(columnIndex));
}
}
package com.sunwii.mybatis.typehandle;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import com.sunwii.mybatis.util.ArrayUtil;
/**
* -必須實(shí)現(xiàn)所有方法,不然的話查詢有可能查詢到為null
* @author Administrator
*
*/
public class ListTypeHandler implements TypeHandler<List<?>> {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void setParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException {
String[] strArr = ArrayUtil.fromList((List<String>) parameter);
String strs = ArrayUtil.asString(",", strArr);
ps.setString(i, strs);
}
@Override
public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
List<String> list = null;
String strs = rs.getString(columnName);
if (strs != null && strs.length() > 0) {
list = Arrays.asList(strs.split(","));
}
return list;
}
@Override
public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
List<String> list = null;
String strs = rs.getString(columnIndex);
if (strs != null && strs.length() > 0) {
list = Arrays.asList(strs.split(","));
}
return list;
}
@Override
public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
List<String> list = null;
String strs = cs.getString(columnIndex);
if (strs != null && strs.length() > 0) {
list = Arrays.asList(strs.split(","));
}
return list;
}
}
用到的數(shù)組集合轉(zhuǎn)換工具類:
package com.sunwii.mybatis.util;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ArrayUtil {
@SuppressWarnings("unchecked")
public static <T> List<T> asList(T... args) {
return Arrays.asList(args);
}
public static <T> List<T> asListFromSet(Set<T> set) {
if (set == null || set.size() < 1) {
return null;
}
List<T> list = new ArrayList<T>();
for (T t : set) {
list.add(t);
}
return list;
}
public static <T> List<T> asListFromArray(T[] array) {
if (array == null || array.length < 1) {
return null;
}
List<T> list = new ArrayList<T>();
for (T t : array) {
list.add(t);
}
return list;
}
public static <T> List<T> asListFromMapKey(Map<T, ?> map) {
if (map == null || map.size() < 1) {
return null;
}
return ArrayUtil.asListFromSet(map.keySet());
}
public static <T> List<T> asListFromMapValue(Map<?, T> map) {
if (map == null || map.size() < 1) {
return null;
}
List<T> list = new ArrayList<T>();
Collection<T> values = map.values();
for (T t : values) {
list.add(t);
}
return list;
}
@SuppressWarnings("unchecked")
public static <T> T[] fromArray(T... args) {
if (args == null || args.length < 1) {
return null;
}
T[] array = (T[]) Array.newInstance(args[0].getClass(), args.length);
for (int i = 0; i < args.length; i++) {
array[i] = args[i];
}
return array;
}
@SuppressWarnings("unchecked")
public static <T> T[] fromList(List<T> list) {
if (list == null || list.size() < 1) {
return null;
}
Class<T> clz = null;
for (T t : list) {
clz = (Class<T>) t.getClass();
break;
}
T[] array = (T[]) Array.newInstance(clz, list.size());
int i = 0;
for (T t : list) {
array[i] = t;
i++;
}
return array;
}
@SuppressWarnings("unchecked")
public static <T> T[] fromSet(Set<T> set) {
if (set == null || set.size() < 1) {
return null;
}
Class<T> clz = null;
for (T t : set) {
clz = (Class<T>) t.getClass();
break;
}
T[] array = (T[]) Array.newInstance(clz, set.size());
int i = 0;
for (T t : set) {
array[i] = t;
i++;
}
return array;
}
public static <T> T[] fromMapKey(Map<T, ?> map) {
if (map == null || map.size() < 1) {
return null;
}
Set<T> set = map.keySet();
return ArrayUtil.fromSet(set);
}
public static <T> T[] fromMapValue(Map<?, T> map) {
if (map == null || map.size() < 1) {
return null;
}
List<T> list = new ArrayList<T>();
Collection<T> values = map.values();
for (T t : values) {
list.add(t);
}
return ArrayUtil.fromList(list);
}
@SuppressWarnings("unchecked")
public static <T> Set<T> asSet(T... args) {
if (args == null || args.length < 1) {
return null;
}
Set<T> set = new HashSet<T>();
for (int i = 0; i < args.length; i++) {
if (!set.contains(args[i])) {
set.add(args[i]);
}
}
return set;
}
public static <T> Set<T> asSetFromArray(T[] array) {
if (array == null || array.length < 1) {
return null;
}
Set<T> set = new HashSet<T>();
for (T t : array) {
set.add(t);
}
return set;
}
public static <T> Set<T> asSetFromMapKey(Map<T, ?> map) {
if (map == null || map.size() < 1) {
return null;
}
return map.keySet();
}
public static <T> Set<T> asSetFromMapValue(Map<?, T> map) {
if (map == null || map.size() < 1) {
return null;
}
Set<T> set = new HashSet<T>();
Collection<T> values = map.values();
for (T t : values) {
set.add(t);
}
return set;
}
public static <T1, T2> Map<T1, T2> asMapFrom(Set<T1> keySet, Set<T2> valueSet) {
if (keySet == null || keySet.size() < 1 || valueSet == null || valueSet.size() < 1) {
return null;
}
Map<T1, T2> map = new HashMap<T1, T2>();
List<T2> list = ArrayUtil.asListFromSet(valueSet);
int i = 0;
for (T1 t : keySet) {
try {
map.put(t, list.get(i++));
} catch (Exception e) {// 超長
map.put(t, null);
}
}
return map;
}
@SuppressWarnings("unchecked")
public static <T> String asString(String separator, T... args) {
if (args == null || args.length < 1) {
return null;
}
StringBuilder sp = new StringBuilder();
for (int i = 0; i < args.length; i++) {
sp.append(args[i]);
if (i != args.length - 1) {
sp.append(separator);
}
}
return sp.toString();
}
}
Mapper接口:UserMapper.java
package com.sunwii.mybatis.mapper;
import java.util.List;
import com.sunwii.mybatis.bean.User;
public interface UserMapper {
public User selectById(int id);
public List<User> selectByName(String name);
public int insert(User user);
public int update(User user);
public int delete(int id);
}
映射文件:UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sunwii.mybatis.mapper.UserMapper">
<select id="selectById" parameterType="Integer"
resultType="User">
select * from t_user where id = #{id}
</select>
<select id="selectByName" parameterType="String"
resultType="User">
select * from t_user where name like "%"#{name}"%"
</select>
<insert id="insert">
insert into
t_user(
name, birthday, vip, salary, height, lastlogin,level,state,sex,tels
)values(
#{name},
#{birthday},
#{vip},
#{salary},
#{height},
#{lastlogin},
#{level},
#{state},
#{sex},
#{tels,typeHandler=com.sunwii.mybatis.typehandle.ListTypeHandler}
)
</insert>
<update id="update">
update t_user set
name=#{name},
birthday=#{birthday},
vip=#{vip},
salary=#{salary},
height=#{height},
lastlogin=#{lastlogin},
level=#{level},
state=#{state},
sex=#{sex},
tels=#{tels,typeHandler=com.sunwii.mybatis.typehandle.ListTypeHandler}
where id=#{id}
</update>
<delete id="delete" parameterType="Integer">
delete from t_user where
id=#{id}
</delete>
</mapper>
日期工具:CurrentUtil.java
package com.sunwii.mybatis.util;
import java.sql.Timestamp;
import java.util.Date;
public class CurrentUtil {
public static long currentTime() {
return new Date().getTime();
}
public static Date currentDate() {
return new Date();
}
public static java.sql.Date currentSqlDate() {
return new java.sql.Date(currentTime());
}
public static Timestamp currentTimestamp() {
return new java.sql.Timestamp(currentTime());
}
}
測試示例:
package com.sunwii.mybatis.test.mapper;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import com.sunwii.mybatis.bean.User;
import com.sunwii.mybatis.enums.Level;
import com.sunwii.mybatis.enums.Sex;
import com.sunwii.mybatis.enums.State;
import com.sunwii.mybatis.mapper.UserMapper;
import com.sunwii.mybatis.test.insert.TestInsert;
import com.sunwii.mybatis.util.CurrentUtil;
import com.sunwii.mybatis.util.SessionFactoryUtil;
public class testMapper {
private static Log log = LogFactory.getLog(TestInsert.class);
private static SqlSessionFactory sf = SessionFactoryUtil.creat("mybatis-config.xml", true);
@Test
public void testMapperInsert() {
User user = new User();
//user.setId(50);
user.setName("sunwii");
user.setVip(1);
user.setSalary(3333.00);
user.setHeight(1.70f);
user.setBirthday(CurrentUtil.currentDate());
user.setLastlogin(CurrentUtil.currentTimestamp());
user.setLevel(Level.LEVEL_3);
user.setState(State.OK);
user.setSex(Sex.WOMAN);
user.setTels(Arrays.asList("133xxxxxxx", "159xxxxxxxx"));
int rs = 0;
SqlSession session = sf.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
try {
rs = userMapper.insert(user);
session.commit();
} catch (Exception e) {
rs = 0;
session.rollback();
e.printStackTrace();
} finally {
session.close();
}
log.info("操作結(jié)果:" + rs);
}
@Test
public void testMapperUpdate() {
User user = new User();
user.setId(1);
user.setName("sunwii--55550");
user.setVip(1);
user.setSalary(3333.00);
user.setHeight(1.70f);
user.setBirthday(CurrentUtil.currentDate());
user.setLastlogin(CurrentUtil.currentTimestamp());
user.setLevel(Level.LEVEL_2);
user.setState(State.ERROR);
user.setSex(Sex.MAN);
user.setTels(Arrays.asList("136xxxxxx", "139xxxxxxx"));
int rs = 0;
SqlSession session = sf.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
try {
rs = userMapper.update(user);
session.commit();
} catch (Exception e) {
rs = 0;
session.rollback();
e.printStackTrace();
} finally {
session.close();
}
log.info("操作結(jié)果:" + rs);
}
@Test
public void testMapperDelete() {
User user = new User(50);
int rs = 0;
SqlSession session = sf.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
try {
rs = userMapper.delete(user.getId());
session.commit();
} catch (Exception e) {
rs = 0;
session.rollback();
e.printStackTrace();
} finally {
session.close();
}
log.info("操作結(jié)果:" + rs);
}
@Test
public void testMapperGetOne() {
Integer id = 50;
User user = null;
SqlSession session = sf.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
user = userMapper.selectById(id);
log.info(user);
}
@Test
public void testMapperGetList() {
String userName = "sunwii";
List<User> users = null;
SqlSession session = sf.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
users = userMapper.selectByName(userName);
for (User user : users) {
log.info(user);
}
}
}
<<Mybatis總結(jié)之如何自動生成數(shù)據(jù)庫表結(jié)構(gòu)>>
說明:
這里多余的步驟僅僅是為了存檔下代碼(以及方便一些初學(xué)者不看代碼不知道怎么回事的原因:里邊涉及了各種常用類型的轉(zhuǎn)換和映射)。
本文中最重要的就是Hibernate的幾個包的選取,以及配置文件的精簡,還有就是加載Hibernate的SessionFactory的方法。
這些說來說去都是Hibernate的東西。跟Mybatis原本是沒有一點(diǎn)關(guān)系的。只不過需要用于,那純屬相當(dāng)于復(fù)習(xí)一下Hibernate了。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。
相關(guān)文章
java正則表達(dá)式獲取指定HTML標(biāo)簽的指定屬性值且替換的方法
下面小編就為大家?guī)硪黄猨ava正則表達(dá)式獲取指定HTML標(biāo)簽的指定屬性值且替換的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12
SpringBoot之那些注入不了的Spring占位符(${}表達(dá)式)問題
這篇文章主要介紹了SpringBoot之那些注入不了的Spring占位符(${}表達(dá)式)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
Spring事務(wù)管理下synchronized鎖失效問題的解決方法
這篇文章主要給大家介紹了關(guān)于Spring事務(wù)管理下synchronized鎖失效問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03
Java實(shí)現(xiàn)隊(duì)列的三種方法集合
這篇文章主要介紹了Java實(shí)現(xiàn)隊(duì)列的三種方法集合,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
詳解SpringCloud Ribbon 負(fù)載均衡通過服務(wù)器名無法連接的神坑
這篇文章主要介紹了詳解SpringCloud Ribbon 負(fù)載均衡通過服務(wù)器名無法連接的神坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06
java實(shí)現(xiàn)的2048游戲完整實(shí)例
這篇文章主要介紹了java實(shí)現(xiàn)的2048游戲,結(jié)合完整實(shí)例形式分析了java實(shí)現(xiàn)2048游戲功能的相關(guān)數(shù)值運(yùn)算、swing組件布局、事件響應(yīng)等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
Java實(shí)現(xiàn)獲取控制臺輸出結(jié)果轉(zhuǎn)換為變量的詳細(xì)操作
在Java編程中,有時(shí)需將控制臺的輸出捕獲為字符串,以便于后續(xù)的處理或測試,這種需求在日志記錄、單元測試或調(diào)試時(shí)尤為常見,下面,將通過詳細(xì)步驟來介紹如何使用ByteArrayOutputStream和PrintStream來實(shí)現(xiàn)這一功能,需要的朋友可以參考下2024-06-06

