mybatis是一款优秀的半自动持久层框架,它支持自定义SQL、存储过程以及高级映射。mybatis免除了几乎所有jdbc代码以及设置参数和获取结果集的工作。mybatis可以通过简单的xml或注解来配置和映射原始类型、接口和java pojo(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过SqlSessionFactoryBuilder 获得。SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例
mybatis-config.xml
<configuration>
<properties resource="database.properties">properties>
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/user/dao/UserMapper.xml"/>
mappers>
configuration>
UserMapper.xml
<mapper namespace="com.user.dao.UserMapper">
<select id="count" resultType="int">
select count(*) from users
select>
mapper>
MybatisUtil.java
package com.user.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtil {
private static SqlSessionFactory factory;
static{
//静态代码块的作用就是再类加载的时候只执行一次,初始化了SqlSessionFactory对象
InputStream is;
try {
is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取sqlsession
* @return
*/
public static SqlSession createSqlSession(){
return factory.openSession();
}
/**
* 关闭sqlSession对象
* @param sqlsession
*/
public static void closeSqlSession(SqlSession sqlsession){
if(null!=sqlsession){
sqlsession.close();
}
}
}
它在命名空间 “com.user.dao.UserMapper” 中定义了一个名为 “count” 的映射语句,这样你就可以用全限定名 “com.user.dao.UserMapper.count” 来调用映射语句了。
测试类:TestUserMapper.java
package test;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.user.util.MybatisUtil;
public class TestUserMapper {
private Logger logger = Logger.getLogger(TestUserMapper.class);
@Test
public void test() {
int count = 0;
SqlSession sqlSession = null;
try {
//实例化SqlSession对象
sqlSession = MybatisUtil.createSqlSession();
//通过命名空间调用sql语句
count = sqlSession.selectList("com.user.dao.UserMapper.count");
//日志debug打印
logger.debug("学生数量:----------"+count);
//提交事务
sqlSession.commit();
} catch (Exception e) {
//事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally{
//关闭SqlSession
MybatisUtil.closeSqlSession(sqlSession);
}
}
}
最常用方式,注意,接口里面的count()方法一定要和UserMapper.xml映射文件的id一致
接口:UserMapper.java
package com.user.dao;
public interface UserMapper {
//方法名必须和UserMapper.xml映射文件的id一致
int count();
}
测试类:TestUserMapper.java
package test;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.user.dao.UserMapper;
import com.user.util.MybatisUtil;
public class TestUserMapper {
private Logger logger = Logger.getLogger(TestUserMapper.class);
@Test
public void test() {
int count = 0;
SqlSession sqlSession = null;
try {
//实例化SqlSession对象
sqlSession = MybatisUtil.createSqlSession();
//得到接口映射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//通过调用接口方法来调用sql语句
count = mapper.count();
logger.debug("学生数量:----------"+count);
//提交事务
sqlSession.commit();
} catch (Exception e) {
//事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally{
MybatisUtil.closeSqlSession(sqlSession);
}
}
}
UserMapper.java
package com.user.dao;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.user.projo.User;
public interface UserMapper {
public int add(User user);
}
UserMapper.xml
<mapper namespace="com.user.dao.UserMapper">
<insert id="add" parameterType="User">
insert into users values(#{id},#{userCode},#{userName},to_date(#{birthday},'yyyy-MM-dd'))
insert>
mapper>
UserMapper.java
package com.user.dao;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.user.projo.User;
public interface UserMapper {
public int delete(@Param("dId")int id);
}
UserMapper.xml
<mapper namespace="com.user.dao.UserMapper">
<delete id="delete" parameterType="int">
delete from users where id=#{dId}
delete>
mapper>
UserMapper.java
package com.user.dao;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.user.projo.User;
public interface UserMapper {
public int modify(User user);
//注解方式
public int updateUserName(@Param("username")String userName,@Param("uId")int id);
}
UserMapper.xml
<mapper namespace="com.user.dao.UserMapper">
<update id="modify" parameterType="User">
update users
set
usercode=#{userCode},
username=#{userName},
birthday=to_date(#{birthday},'yyyy-MM-dd')
where id=#{id}
update>
<update id="updateUserName">
update users
set
username=#{username}
where id=#{uId}
update>
mapper>
UserMapper.java
package com.user.dao;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.user.projo.User;
public interface UserMapper {
public List<User> selectUserList();
public List<User> selectUserListByName(String username);
public User selectUserByCodeAndId(@Param("code")String userCode,@Param("userID")int id);
public List<User> selectUserListByUser(User user);
public List<User> selectUserListByMap(HashMap<String, String> map);
}
UserMapper.xml
<select id="count" resultType="int">
select count(*) from users
select>
<select id="selectUserList" resultType="User">
select * from users
select>
<select id="selectUserListByName" resultType="User" parameterType="String">
select * from users where username like concat('%',concat(#{userName},'%'))
select>
<select id="selectUserByCodeAndId" resultType="User">
select * from users where usercode=#{code} and id=#{userID}
select>
<select id="selectUserListByUser" resultType="User" parameterType="User">
select * from users where usercode=#{userCode} and
username like concat('%',concat(#{userName},'%'))
select>
<select id="selectUserListByMap" resultType="User" parameterType="Map">
select * from users where usercode=#{codeKey} and username like concat('%',concat(#{nameKey},'%'))
select>
用户类:User.java
package com.user.projo;
import java.util.Date;
public class User {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色ID
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer age;//年龄
//一对一关系
private Role role; //用户角色
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Integer getAge() {
Date date = new Date();
Integer age = date.getYear()-birthday.getYear();
return age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
角色类:Role.java
package com.user.projo;
import java.util.Date;
public class Role {
private Integer id; //id
private String roleCode; //角色编码
private String roleName; //角色名称
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate;//更新时间
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
UserMapper.xml
MyBatis 中在对查询进行 select 映射的时候,返回类型可以用 resultType 也可以用 resultMap ,resultType和 resultMap 有一定关联和区别,应用场景也不同。
<mapper namespace="com.user.dao.UserMapper">
<resultMap type="Role" id="roleResult">
<id property="id" column="r_id"/>
<result property="roleCode" column="rolecode"/>
<result property="roleName" column="rolename"/>
resultMap>
<resultMap type="User" id="UserResult">
<result property="id" column="id" />
<result property="userName" column="username"/>
<association property="role" javaType="Role" resultMap="roleResult"/>
resultMap>
<select id="getUserList" parameterType="User" resultMap="UserResult">
select u.*,r.rolename,r.id r_id
from smbms_user u,smbms_role r
where u.userrole=r.id
and u.username like
concat(#{userName},'%')
and u.userrole=#{userRole}
select>
mapper>
接口:UserMapper.java
package com.user.dao;
import java.util.List;
import com.user.projo.User;
public interface UserMapper {
List<User> getUserList(User user);
}
测试类:TestUserMapper.java
package test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.user.dao.UserMapper;
import com.user.projo.User;
import com.user.util.MybatisUtil;
public class TestUserMapper {
@Test
public void test() {
List<User> list = null;
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.createSqlSession();
User user = new User();
user.setUserName("张");
user.setUserRole(1);
list = sqlSession.getMapper(UserMapper.class).getUserList(user);
for (User u : list) {
System.out.println("------"+
u.getUserName()+"\t"+
u.getBirthday()+"\t"+
u.getRole().getRoleName()
);
}
//提交事务
sqlSession.commit();
} catch (Exception e) {
//事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally{
MybatisUtil.closeSqlSession(sqlSession);
}
}
}
User.java
package com.user.projo;
import java.util.Date;
import java.util.List;
public class User {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色ID
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer age; //年龄
//一对多关系
private List<Address> addressList;//用户地址
public Integer getAge() {
Date date = new Date();
Integer age = date.getYear()-birthday.getYear();
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> addressList) {
this.addressList = addressList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
Address.java
package com.user.projo;
import java.util.Date;
public class Address {
private Integer id; //主键ID
private String postCode; //邮编
private String contact; //联系人
private String addressDesc; //地址
private String tel; //联系电话
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer userId; //用户ID
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getAddressDesc() {
return addressDesc;
}
public void setAddressDesc(String addressDesc) {
this.addressDesc = addressDesc;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
UserMapper.xml
<mapper namespace="com.user.dao.UserMapper">
<resultMap type="User" id="UserResult">
<result property="id" column="id" />
<result property="userName" column="username"/>
<collection property="addressList" ofType="Address" resultMap="addressResult">collection>
resultMap>
<resultMap type="Address" id="addressResult">
<id property="id" column="a_id" />
<result property="postCode" column="postcode" />
<result property="contact" column="contact" />
<result property="addressDesc" column="addressdesc" />
resultMap>
<select id="getAddressListByUserId" parameterType="Integer" resultMap="UserResult">
select u.*,a.id a_id,a.contact,a.addressdesc from smbms_user u
left join smbms_address a on u.id=a.userid
where u.id=#{uid}
select>
mapper>
接口:UserMapper.java
package com.user.dao;
import org.apache.ibatis.annotations.Param;
import com.user.projo.User;
public interface UserMapper {
User getAddressListByUserId(@Param("uid")Integer userId);
}
测试类:TestUserMapper.java
package test;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.user.dao.UserMapper;
import com.user.projo.Address;
import com.user.projo.User;
import com.user.util.MybatisUtil;
public class TestUserMapper {
private Logger logger = Logger.getLogger(TestUserMapper.class);
@Test
public void test() {
User user = null;
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtil.createSqlSession();
//根据userId查询到该用户的地址列表(一对多)
user = sqlSession.getMapper(UserMapper.class).getAddressListByUserId(0);
if(user!=null){
logger.debug("--------------userInfo:"+user.getUserCode()+"\t"+user.getUserName());
if(user.getAddressList().size()>0){
for (Address address : user.getAddressList()) {
logger.debug("---------userAddress:"+address.getId()+"\t"+
address.getContact()+"\t"+address.getAddressDesc());
}
}else{
logger.debug("无地址列表");
}
}else{
logger.debug("无用户");
}
//提交事务
sqlSession.commit();
} catch (Exception e) {
//事务回滚
sqlSession.rollback();
e.printStackTrace();
}finally{
MybatisUtil.closeSqlSession(sqlSession);
}
}
}
mybatis提供查询缓存,用于减轻数据库压力,提高数据库性能
在操作数据库时,需要构造sqlsession对象,在对象中有一个数据结构(HashMap)用于存储缓存数据不同的sqlsession之间的缓存区域是互相不影响的。
mybatis自动开启,并且关闭不了的,可以手动清除缓存。
多个sqlsession去操作同一个mapper的sql语句,多个sqlsession可以共用二级缓存,所得到的数 据会存在二级缓存区域,二级缓存是跨sqlsession的。
mybatis的全局配置文件中配置Setting属性
<settings>
<setting name="cacheEnabled" value="true"/>
settings>
mapeer映射文件中开启二级缓存
<cache/>
就是在需要用到数据的时候才进行加载,不需要用到数据的时候就不加载数据。延迟加载也称为懒加载。
mybatis-config.xml
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
settings>
如果你不想设置全局加载,mybati s提供了局部延时加载功能
fetchType= "1azy/eager"设置延迟或者立即加载,默认延迟
<mapper namespace="com.user.dao.UserMapper">
<select id="selectUserListByConditions1" resultType="User">
select * from smbms_user where 1=1
<if test="userName!=null and userName!=''">
and username like concat(#{userName},'%')
if>
<if test="id!=null">
and id=#{id}
if>
select>
<select id="selectUserListByConditions2" resultType="User">
select * from smbms_user
<where>
<if test="userName!=null and userName!=''">
and username like concat(#{userName},'%')
if>
<if test="id!=null">
and id=#{id}
if>
where>
select>
<select id="selectUserListByConditions3" resultType="User">
select * from smbms_user
<trim prefix="where" prefixOverrides="and | or">
<if test="userName!=null and userName!=''">
and username like concat(#{userName},'%')
if>
<if test="id!=null">
and id=#{id}
if>
trim>
select>
<mapper namespace="com.user.dao.UserMapper">
<select id="selectUserListByConditions4" resultType="User">
select * from smbms_user where 1=1
<choose>
<when test="userName!=null and userName!=''">
and username like concat(#{userName},'%')
when>
<when test="id!=null">
and id=#{id}
when>
<otherwise>
and birthday=#{birthday}
otherwise>
choose>
select>
<update id="modify1">
update smbms_user
set
usercode=#{userCode},
username=#{userName},
birthday=to_date(#{birthday},'yyyy-MM-dd')
where id=#{id}
update>
<update id="modify2">
update smbms_user
<set>
<if test="userCode!=null">usercode=#{userCode},if>
<if test="userCode!=null">username=#{userName},if>
<if test="userCode!=null">birthday=to_date(#{birthday},'yyyy-MM-dd')if>
set>
where id=#{id}
update>
<update id="modify3">
update smbms_user
<trim prefix="set" suffixOverrides="," suffix="where id=#{id}">
<if test="userCode!=null">usercode=#{userCode},if>
<if test="userCode!=null">username=#{userName},if>
<if test="userCode!=null">birthday=to_date(#{birthday},'yyyy-MM-dd'),if>
trim>
update>
<mapper namespace="com.user.dao.UserMapper">
<select id="getUserByRoleId_foreach_array" resultType="User">
select * from smbms_user where userRole in
<foreach collection="array" item="roleIds" open="(" separator="," close=")">
#{roleIds}
foreach>
select>
<select id="getUserByRoleId_foreach_list" resultType="User">
select * from smbms_user where userRole in
<foreach collection="list" item="rolelist" open="(" separator="," close=")">
#{rolelist}
foreach>
select>
<select id="getUserByRoleId_foreach_map" resultType="User">
select * from smbms_user where userRole in
<foreach collection="rkey" item="roleMap" open="(" separator="," close=")">
#{roleMap}
foreach>
select>
mapper>
“http://mybatis.org/dtd/mybatis-3-mapper.dtd”>
```