Mybatis快速入门
Mybatis开发步骤
- 添加依赖坐标
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
- 编写POJO映射文件,如UserMapper.xml 可放在resource资源目录下,注意.和/的区别
<?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=\"userMapper\">
<select id=\"findAll\" resultType=\"com.rsk.entity.User\">
select * from user
</select>
</mapper>
- 编写mybatis配置文件,mybatis-config.xml
<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Mapper 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_db?serverTimezone=GMT%2B8\"/>
<property name=\"username\" value=\"root\"/>
<property name=\"password\" value=\"\"/>
</dataSource>
</environment>
</environments>
<!--加载映射文件-->
<mappers>
<mapper resource=\"com/rsk/mapper/UserMapper.xml\"></mapper>
</mappers>
</configuration>
- 编写测试类
public class Test1 {
@Test
public void test1() throws IOException {
//获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream(\"mybatis-config.xml\");
//获得sqlSession工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作
List<User> users = sqlSession.selectList(\"userMapper.findAll\");
System.out.println(users);
//释放资源
sqlSession.close();
}
}
Mybatis传统增删改查方式
mapper.xml
<mapper namespace=\"userMapper\">
<!--查询操作-->
<select id=\"findAll\" resultType=\"com.rsk.entity.User\">
select * from user
</select>
<!--插入操作-->
<insert id=\"addUser\" parameterType=\"com.rsk.entity.User\">
insert into user values(#{id},#{name},#{pwd})
</insert>
<!--更新操作-->
<update id=\"update\" parameterType=\"com.rsk.entity.User\">
update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
<!--删除操作-->
<delete id=\"delete\" parameterType=\"java.lang.Integer\">
delete from user where id=#{id}
</delete>
</mapper>
Test.java
//获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream(\"mybatis-config.xml\");
//获得sqlSession工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//查询操作
//List<User> users = sqlSession.selectList(\"userMapper.findAll\");
//插入操作
//int insert = sqlSession.insert(\"userMapper.addUser\", user);
//更新操作
//sqlSession.update(\"userMapper.update\", user);
//删除操作
sqlSession.delete(\"userMapper.delete\", 26);
sqlSession.commit();
//释放资源
sqlSession.close();
Mybatis核心标签
- properties:加载外部的properties文件
<!--通过标签加载外部properties文件-->
<properties resource=\"jdbc.properties\"></properties>
- typeAliases:设置类型别名,该标签必须在environments标签上面
<!--别名设置-->
<typeAliases>
<typeAlias type=\"com.rsk.entity.User\" alias=\"user\"></typeAlias>
</typeAliases>
- mappers:加载映射配置
<!--加载映射文件-->
<mappers>
<mapper resource=\"com/rsk/mapper/UserMapper.xml\"></mapper>
</mappers>
- enviroments:数据库环境配置标签
<!--数据源环境-->
<environments default=\"development\">
<environment id=\"development\">
<!--指定事务管理类型,为JDBC(依赖数据源获得连接来管理事务)或者MANAGED(让容器管理事务,默认情况下会关闭连接)-->
<transactionManager type=\"JDBC\"></transactionManager>
<!--指定数据源类型,UNPOOLED(数据源每次被请求时候打开或者关闭连接,POOLED(利用连接池将JDBC对象组织起来),JNDI(用于EJB或者应用服务器容器使用))-->
<dataSource type=\"POOLED\">
<property name=\"driver\" value=\"${jdbc.driver}\"/>
<property name=\"url\" value=\"${jdbc.url}?serverTimezone=GMT%2B8\"/>
<property name=\"username\" value=\"${jdbc.username}\"/>
<property name=\"password\" value=\"\"/>
</dataSource>
</environment>
</environments>
Mybatis代理实现DAO层
采用Mybatis的代理开发实现DAO层,我们只需要编写Mapper接口(相当于DAO接口),然后由Mybatis框架根据接口定义创建接口的动态代理对象,该动态代理对象的方法体相当于是DAO层的实现类方法。遵循以下规范:
- Mapper.xml中的namespace与mapper接口的全限定名称相同
- Mapper.xml中的每个statement的id和Mapper接口方法名相同
- Mapper.xml中的每个sql的parameterType与和Mapper接口方法的输入参数类型相同
- Mapper.xml中的每个sql的resultType与和Mapper接口方法的返回参数类型相同
- 编写DAO接口UserMapper.class
public interface UserMapper {
public List<User> findAll() throws IOException;
public User findById(int id);
}
- 编写映射文件UserMapper.xml,namespace需要指定到DAO接口的位置
<?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.rsk.dao.UserMapper\">
<!--查询操作-->
<select id=\"findAll\" resultType=\"user\">
select * from user
</select>
<select id=\"findById\" parameterType=\"int\" resultType=\"user\">
select * from user where id=#{id}
</select>
<!--插入操作-->
<insert id=\"addUser\" parameterType=\"com.rsk.entity.User\">
insert into user values(#{id},#{name},#{pwd})
</insert>
<!--更新操作-->
<update id=\"update\" parameterType=\"com.rsk.entity.User\">
update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
<!--删除操作-->
<delete id=\"delete\" parameterType=\"java.lang.Integer\">
delete from user where id=#{id}
</delete>
</mapper>
- Service调用sqlSession的getMapper方法
public class ServiceDemo {
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream(\"mybatis-config.xml\");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> all = userMapper.findAll();
User user = userMapper.findById(1);
System.out.println(all);
System.out.println(user.getName());
}
}
动态sql
面对复杂的业务逻辑,SQL需要进行动态调整,如果对每个不同条件专门写一条sql则需要写多个接口中的方法,因此可以选择动态生成SQL语句,从而减少代码量
<where><if></if></where>
标签:条件判断后拼接
<!--动态SQL查询-->
<select id=\"findByCondition\" parameterType=\"user\" resultType=\"user\">
select * from user
<where>
<if test=\"id!=0\">
and id=#{id}
</if>
<if test=\"name!=null\">
and name=#{name}
</if>
<if test=\"pwd!=null\">
and pwd=#{pwd}
</if>
</where>
</select>
对应的接口中的方法:
//条件查询
public List<User> findByCondition(User user);
测试环境中的代码:
@Test
public void test2(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//条件对象
User user = new User();
user.setId(1);
List<User> all = mapper.findByCondition(user);
System.out.println(all);
}
<foreach>
标签:循环拼接
<!--动态SQL查询-->
<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>
对应接口中的方法:
public List<User> findByIds(List<Integer> ids);
对应测试代码:
@Test
public void tests(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//条件对象
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
List<User> all = mapper.findByIds(ids);
System.out.println(all);
}
sql语句抽取
将动态SQL共用的sql语句代码段进行提取,避免修改表名时修改全部的sql,达到sql片段重用的目的
<!--sql语句片段抽取-->
<sql id=\"selectUser\">select * from user</sql>
/*sql语句片段引入*/
<include refid=\"selectUser\"></include>
一对一查询
主要难点在于查询出来的数据包含两个实体类的属性,需要利用resultMap标签进行配置,course类实体需要拥有user成员对象
CourseMapper.xml
<resultMap id=\"courseMap\" type=\"com.rsk.entity.Course\">
<!--手动指定字段与实体属性间的映射关系-->
<id column=\"cid\" property=\"id\"></id>
<result column=\"cno\" property=\"cno\"></result>
<result column=\"cname\" property=\"cname\"></result>
<!--配置外键所在表的映射关系-->
<association property=\"user\" javaType=\"com.rsk.entity.User\">
<id column=\"uid\" property=\"id\"></id>
<result column=\"name\" property=\"name\"/>
<result column=\"pwd\" property=\"pwd\"/>
</association>
</resultMap>
<select id=\"findAll\" resultMap=\"courseMap\">
select *, c.id cid
from course c, user u where c.uid=u.id
</select>
test
@Test
public void test5(){
CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
List<Course> all = mapper.findAll();
System.out.println(all);
}
来源:https://www.cnblogs.com/rskblog/p/16259587.html
本站部分图文来源于网络,如有侵权请联系删除。