①导入MyBatis的坐标和其他相关坐标
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.32version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
dependencies>
public class User {
private int id;
private String username;
private String password;
//省略get、set、toString方法
}
④ 编写映射文件UserMapper.xml
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
<select id="findAll" resultType="com.lenyoo.domain.User">
select * from user
select>
mapper>
⑤ 编写核心文件SqlMapConfig.xml
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="WLY755414220"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/lenyoo/mapper/UserMapper.xml">mapper>
mappers>
configuration>
⑥ 编写测试类
public class MyBatisTest {
@Test
public void test1() throws IOException {
// 获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获得sqlSession会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行操作 参数:namespace + id
List<User> userList = sqlSession.selectList("userMapper.findAll");
// 打印数据
System.out.println(userList);
// 释放资源
sqlSession.close();
}
}
① 编写UserMapper映射文件
<mapper namespace="userMapper">
<insert id="save" parameterType="com.lenyoo.domain.User">
insert into user values(#{id},#{username},#{password})
insert>
mapper>
②编写插入实体User的代码
@Test
public void test2() throws IOException {
// 模拟user对象
User user = new User();
user.setUsername("tom");
user.setPassword("abc");
// 获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获得sqlSession会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行操作 参数:namespace + id
sqlSession.insert("userMapper.save",user);
// mybatis执行更新操作 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
注意:
① 编写UserMapper映射文件
<mapper namespace="userMapper">
<update id="update" parameterType="com.lenyoo.domain.User">
update user set username=#{username},password=#{password} where id=#{id}
update>
mapper>
②编写插入实体User的代码
@Test
// 修改操作
public void test3() throws IOException {
// 模拟user对象
User user = new User();
user.setId(7);
user.setUsername("lucy");
user.setPassword("123");
// 获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获得sqlSession会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行操作 参数:namespace + id
sqlSession.update("userMapper.update",user);
// mybatis执行更新操作 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
注意:
① 编写UserMapper映射文件
<mapper namespace="userMapper">
<delete id="delete" parameterType="java.lang.Integer">
delete from user where id=#{id}
delete>
mapper>
②编写删除数据的代码
@Test
// 删除操作
public void test4() throws IOException {
// 获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获得sqlSession会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行操作 参数:namespace + id
sqlSession.delete("userMapper.delete",7);
// mybatis执行更新操作 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
注意:
数据库环境的配置,支持多环境配置
事务管理器(transactionManager)类型有两种:
数据源(dataSource)类型有三种:
• UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。
• POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来。
• JNDI:这个数据源的实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。
该标签的作用是加载映射的,加载方式有如下几种:
• 使用相对于类路径的资源引用,例如:
• 使用完全限定资源定位符(URL),例如:
• 使用映射器接口实现类的完全限定类名,例如:
• 将包内的映射器接口实现全部注册为映射器,例如
实际开发中,习惯将数据源的配置信息单独抽取成一个properties文件,该标签可以加载额外配置的properties文件
上面我们是自定义的别名,mybatis框架已经为我们设置好的一些常用的类型的别名
常用API:SqlSessionFactory build(InputStream inputStream)
通过加载mybatis的核心文件的输入流的形式构建一个SqlSessionFactory对象
// 获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获得sqlSession会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession 实例在 MyBatis 中是非常强大的一个类。在这里会看到所有执行语句、提交或回滚事务和获取映射器实例的方法。
执行语句的方法主要有:
<T> T selectOne(String statement, Object parameter)
<E> List<E> selectList(String statement, Object parameter)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
操作事务的方法主要有:
void commit()
void rollback()
采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。
Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接
口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
Mapper 接口开发需要遵循以下规范:
1、 Mapper.xml文件中的namespace与mapper接口的全限定名相同
2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
public class ServiceDemo {
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
System.out.println(all);
User user = mapper.findById(1);
System.out.println(user);
}
}
多条件组合查询
<select id="findByCondition" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=0">
and id=#{id}
if>
<if test="username!=null">
and username=#{username}
if>
<if test="password!=null">
and password=#{password}
if>
where>
select>
循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)
<select id="findByIds" parameterType="list" resultType="user">
select * from user
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
foreach标签的属性含义如下:
标签用于遍历集合,它的属性:
• collection:代表要遍历的集合元素,注意编写时不要写#{}
• open:代表语句的开始部分
• close:代表结束部分
• item:代表遍历集合的每个元素,生成的变量名
• sperator:代表分隔符
Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的
<sql id="selectUser">select * from usersql>
<select id="findByCondition" parameterType="user" resultType="user">
<include refid="selectUser">include>
<where>
<if test="id!=0">
and id=#{id}
if>
<if test="username!=null">
and username=#{username}
if>
<if test="password!=null">
and password=#{password}
if>
where>
select>
<select id="findByIds" parameterType="list" resultType="user">
<include refid="selectUser">include>
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
foreach>
where>
select>
例如:一个Java中的Date数据类型,我想将之存到数据库的时候存成一个1970年至今的毫秒数,取出来时转换成java的Date,即java的Date与数据库的varchar毫秒值之间转换。
开发步骤:
① 定义转换类继承类BaseTypeHandler
② 覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法
public class DateTypeHandler extends BaseTypeHandler<Date> {
@Override
//将java类型 转换成 数据库需要的类型
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i, time);
}
@Override
//将数据库类型 转换成 java类型
//String参数 要转换的字段名称
//ResultSet 查询出的结果
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
}
@Override
//将数据库类型 转换成 java类型
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
Date date = new Date(aLong);
return date;
}
@Override
//将数据库类型 转换成 java类型
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
③ 在MyBatis核心配置文件中进行注册
<typeHandlers>
<typeHandler handler="com.lenyoo.handler.DateTypeHandler">typeHandler>
typeHandlers>
④ 测试转换是否正确
MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据
开发步骤:
① 导入通用PageHelper的坐标
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>3.7.5version>
dependency>
<dependency>
<groupId>com.github.jsqlparsergroupId>
<artifactId>jsqlparserartifactId>
<version>0.9.1version>
dependency>
② 在mybatis核心配置文件中配置PageHelper插件
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
plugin>
plugins>
③ 测试分页数据获取
@Test
public void test3() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//设置分页相关参数 当前页+每页显示的条数
PageHelper.startPage(2,3);
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
//获得与分页相关参数
PageInfo<User> pageInfo = new PageInfo<User>(userList);
System.out.println("当前页:" + pageInfo.getPageNum());
System.out.println("每页显示条数:" + pageInfo.getPageSize());
System.out.println("总条数:" + pageInfo.getTotal());
System.out.println("总页数:" + pageInfo.getPages());
System.out.println("上一页:" + pageInfo.getPrePage());
System.out.println("下一页:" + pageInfo.getNextPage());
System.out.println("是否是第一页:" + pageInfo.isIsFirstPage());
System.out.println("是否是最后一页:" + pageInfo.isIsLastPage());
sqlSession.close();
}
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
select *, o.id oid from orders o, user u where o.uid=u.id
public class Order {
private int id;
private Date orderTime;
private double total;
//表示当前订单属于哪一个用户
private User user;
// 省略getter、setter和toString
}
public class User {
private int id;
private String username;
private String password;
private Date birthday;
// 省略getter、setter和toString
}
public interface OrderMapper {
//查询全部的方法
public List<Order> findAll();
}
<mapper namespace="com.lenyoo.mapper.OrderMapper">
<resultMap id="orderMap" type="order">
<id column="oid" property="id">id>
<result column="ordertime" property="orderTime">result>
<result column="total" property="total">result>
<association property="user" javaType="user">
<id column="uid" property="id">id>
<result column="username" property="username">result>
<result column="password" property="password">result>
<result column="birthday" property="birthday">result>
association>
resultMap>
<select id="findAll" resultMap="orderMap">
select *, o.id oid from orders o, user u where o.uid=u.id
select>
mapper>
OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
List<Order> orderList = mapper.findAll();
for (Order order : orderList) {
System.out.println(order);
}
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
SELECT *, o.id oid FROM user u, orders o WHERE u.id=o.uid
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//描述的是当前用户存在哪些订单
private List<Order> orderList;
// 省略getter、setter和toString
}
public class Order {
private int id;
private Date orderTime;
private double total;
//表示当前订单属于哪一个用户
private User user;
// 省略getter、setter和toString
}
public interface UserMapper {
public List<User> findAll();
}
<mapper namespace="com.lenyoo.mapper.UserMapper">
<resultMap id="userMap" type="user">
<id column="uid" property="id">id>
<result column="username" property="username">result>
<result column="password" property="password">result>
<result column="birthday" property="birthday">result>
<collection property="orderList" ofType="order">
<id column="oid" property="id">id>
<result column="ordertime" property="orderTime">result>
<result column="total" property="total">result>
collection>
resultMap>
<select id="findAll" resultMap="userMap">
SELECT *, o.id oid FROM user u, orders o WHERE u.id=o.uid
select>
mapper>
@Test
public void test2() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
User{id=1, username='zhangsan', password='123', birthday=null, orderList=[Order{id=1, orderTime=Fri Feb 15 14:59:37 CST 2019, total=3000.0, user=null}, Order{id=2, orderTime=Wed Oct 10 15:00:00 CST 2018, total=5800.0, user=null}, Order{id=4, orderTime=Thu Feb 21 15:00:25 CST 2019, total=2345.0, user=null}]}
User{id=2, username='lisi', password='123', birthday=null, orderList=[Order{id=3, orderTime=Thu Feb 28 15:00:14 CST 2019, total=323.0, user=null}, Order{id=5, orderTime=Mon Feb 04 15:00:37 CST 2019, total=100.0, user=null}]}
User{id=3, username='wangwu', password='123', birthday=null, orderList=[Order{id=6, orderTime=Thu Jun 07 15:00:52 CST 2018, total=2009.0, user=null}]}
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
SELECT * FROM user u, sys_user_role ur, sys_role r WHERE u.id=ur.userId AND ur.roleId=r.id
public class Role {
private int id;
private String roleName;
private String roleDesc;
// 省略getter、setter和toString
}
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//描述的是当前用户存在哪些订单
private List<Order> orderList;
//描述的是当前用户具备哪些角色
private List<Role> roleList;
// 省略getter、setter和toString
}
public interface UserMapper {
public List<User> findUserAndRoleAll();
}
<resultMap id="userRoleMap" type="user">
<id column="userId" property="id">id>
<result column="username" property="username">result>
<result column="password" property="password">result>
<result column="birthday" property="birthday">result>
<collection property="roleList" ofType="role">
<id column="roleId" property="id">id>
<result column="roleName" property="roleName">result>
<result column="roleDesc" property="roleDesc">result>
collection>
resultMap>
<select id="findUserAndRoleAll" resultMap="userRoleMap">
SELECT * FROM user u, sys_user_role ur, sys_role r WHERE u.id=ur.userId AND ur.roleId=r.id
select>
@Test
public void test3() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userAndRoleAll = mapper.findUserAndRoleAll();
for (User user : userAndRoleAll) {
System.out.println(user);
}
sqlSession.close();
}
User{id=1, username='zhangsan', password='123', birthday=null, roleList=[Role{id=1, roleName='院长', roleDesc='负责全面工作'}, Role{id=2, roleName='研究员', roleDesc='课程研发工作'}]}
User{id=2, username='lisi', password='123', birthday=null, roleList=[Role{id=2, roleName='研究员', roleDesc='课程研发工作'}, Role{id=3, roleName='讲师', roleDesc='授课工作'}]}
public interface UserMapper {
@Insert("insert into user values(#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update("update user set username=#{username},password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int id);
@Select("select * from user where id=#{id}")
public User findById(int id);
@Select("select * from user")
public List<User> findAll();
}
<mappers>
<package name="com.lenyoo.mapper"/>
mappers>
实现复杂关系映射之前我们可以在映射文件中通过配置
public interface OrderMapper {
//方式一:
@Select("select * from orders")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "orderTime"),
@Result(column = "total",property = "total"),
@Result(
property = "user", //要封装的属性名称
column = "uid", //根据哪个字段去查询user表的数据
javaType = User.class, //要封装的实体类型
//select属性 代表查询哪个接口的方法获得数据
one = @One(select = "com.lenyoo.mapper.UserMapper.findById")
)
})
public List<Order> findAll();
//方式二:
/* @Select("select *, o.id oid from orders o, user u where o.uid=u.id")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "ordertime",property = "orderTime"),
@Result(column = "total",property = "total"),
@Result(column = "uid",property = "user.id"),
@Result(column = "username",property = "user.username"),
@Result(column = "password",property = "user.password")
})
public List findAll();*/
}
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.lenyoo.mapper.OrderMapper.findByUid")
)
})
public List<User> findUserAndOrderAll();
}
public interface OrderMapper {
@Select("select * from orders where uid=#{uid}")
public List<Order> findByUid(int uid);
}
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select = "com.lenyoo.mapper.RoleMapper.findByUid")
)
})
public List<User> findUserAndRoleAll();
}
public interface RoleMapper {
@Select("SELECT * from sys_user_role ur, sys_role r WHERE ur.roleId=r.id AND ur.userId=#{uid}")
public List<Role> findByUid(int uid);
}