Mybatis学习笔记
Posted 普通网友
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis学习笔记相关的知识,希望对你有一定的参考价值。
1. Mybatis介绍(ibatis)
MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录.
JDBC-dbutils(自动封装)-MyBatis-Hibernate
session.get(Class c, id);//查找映射文件(全类名—表名, 属性名与表字段名)/表
select * from users where id=?
User user = session.getSession(userClass,id)
user.setName(“tt”); flush()//脏数据检查 clear();
2. mybatis快速入门
编写第一个基于mybaits的测试例子:
2.1.添加jar包
【mybatis】 mybatis-3.1.1.jar 【mysql驱动包】 |
2.2.建库+表
create database mybatis; use mybatis; CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT); INSERT INTO users(NAME, age) VALUES('Tom', 12); INSERT INTO users(NAME, age) VALUES('Jack', 11); |
2.3. 添加Mybatis的配置文件conf.xml
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> </configuration> |
2.4. 定义表所对应的实体类
public class User private int id; private String name; private int age; //get,set方法
|
2.5. 定义操作users表的sql映射文件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.atguigu.mybatis_test.test1.userMapper"> <select id="getUser" parameterType="int" resultType="com.atguigu.mybatis_test.test1.User"> select * from users where id=#id </select> </mapper> |
2.6. 在conf.xml文件中注册userMapper.xml文件
<mappers> <mapper resource="com/atguigu/mybatis_test/test1/userMapper.xml"/> </mappers> |
2.7. 编写测试代码:执行定义的select语句
public class Test public static void main(String[] args) throws IOException String resource = "conf.xml"; //加载mybatis的配置文件(它也加载关联的映射文件) Reader reader = Resources.getResourceAsReader(resource); //构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //创建能执行映射文件中sql的sqlSession SqlSession session = sessionFactory.openSession(); //映射sql的标识字符串 String statement = "com.atguigu.mybatis.bean.userMapper"+".selectUser"; //执行查询返回一个唯一user对象的sql User user = session.selectOne(statement, 1); System.out.println(user);
|
3. 操作users表的CRUD
3.1. XML的实现
1). 定义sql映射xml文件:
<insert id="insertUser" parameterType="com.atguigu.ibatis.bean.User"> insert into users(name, age) values(#name, #age); </insert>
<delete id="deleteUser" parameterType="int"> delete from users where id=#id </delete>
<update id="updateUser" parameterType="com.atguigu.ibatis.bean.User"> update users set name=#name,age=#age where id=#id </update>
<select id="selectUser" parameterType="int" resultType="com.atguigu.ibatis.bean.User"> select * from users where id=#id </select>
<select id="selectAllUsers" resultType="com.atguigu.ibatis.bean.User"> select * from users </select> |
2). 在config.xml中注册这个映射文件
<mapper resource=" com/atguigu/ibatis/bean/userMapper.xml"/> |
3). 在dao中调用:
public User getUserById(int id) SqlSession session = sessionFactory.openSession(); User user = session.selectOne(URI+".selectUser", id); return user;
|
3.2. 注解的实现
1). 定义sql映射的接口
public interface UserMapper @Insert("insert into users(name, age) values(#name, #age)") public int insertUser(User user);
@Delete("delete from users where id=#id") public int deleteUserById(int id);
@Update("update users set name=#name,age=#age where id=#id") public int updateUser(User user);
@Select("select * from users where id=#id") public User getUserById(int id);
@Select("select * from users") public List<User> getAllUser();
|
2). 在config中注册这个映射接口
<mapper class="com.atguigu.ibatis.crud.ano.UserMapper"/> |
3). 在dao类中调用
public User getUserById(int id) SqlSession session = sessionFactory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); User user = mapper.getUserById(id); return user;
|
4. 几个可以优化的地方
4.1.连接数据库的配置单独放在一个properties文件中
## db.properties
<properties resource="db.properties"/>
<property name="driver" value="$driver" /> <property name="url" value="$url" /> <property name="username" value="$username" /> <property name="password" value="$password" /> |
4.2.为实体类定义别名,简化sql映射xml文件中的引用
<typeAliases> <typeAlias type="com.atguigu.ibatis.bean.User" alias="_User"/> </typeAliases> |
4.3.可以在src下加入log4j的配置文件,打印日志信息
1. 添加jar: log4j-1.2.16.jar
2.1. log4j.properties(方式一)
log4j.properties, log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
2.2. log4j.xml(方式二)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %dMM-dd HH:mm:ss,SSS %m (%F:%L) \\n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="debug" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration> |
5. 解决字段名与实体类属性名不相同的冲突
5.1.准备表和数据:
CREATE TABLE orders( order_id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(20), order_price FLOAT ); INSERT INTO orders(order_no, order_price) VALUES('aaaa', 23); INSERT INTO orders(order_no, order_price) VALUES('bbbb', 33); INSERT INTO orders(order_no, order_price) VALUES('cccc', 22); |
5.2.定义实体类:
public class Order private int id; private String orderNo; private float price;
|
5.3.实现getOrderById(id)的查询:
方式一: 通过在sql语句中定义别名 <select id="selectOrder" parameterType="int" resultType="_Order"> select order_id id, order_no orderNo,order_price price from orders where order_id=#id </select>
方式二: 通过<resultMap> <select id="selectOrderResultMap" parameterType="int" resultMap="orderResultMap"> select * from orders where order_id=#id </select>
<resultMaptype="_Order" id="orderResultMap"> <id property="id" column="order_id"/> <result property="orderNo" column="order_no"/> <result property="price" column="order_price"/> </resultMap> |
6.实现关联表查询
6.1. 一对一关联
1). 提出需求
根据班级id查询班级信息(带老师的信息)
2). 创建表和数据
CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR(20) ); CREATE TABLE class( c_id INT PRIMARY KEY AUTO_INCREMENT, c_name VARCHAR(20), teacher_id INT ); ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id);
INSERT INTO teacher(t_name) VALUES('LS1'); INSERT INTO teacher(t_name) VALUES('LS2');
INSERT INTO class(c_name, teacher_id) VALUES('bj_a', 1); INSERT INTO class(c_name, teacher_id) VALUES('bj_b', 2); |
3). 定义实体类:
public class Teacher private int id; private String name;
public class Classes private int id; private String name; private Teacher teacher;
|
4). 定义sql映射文件ClassMapper.xml
<!-- 方式一:嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集 封装联表查询的数据(去除重复的数据) select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1 --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#id </select> <resultMap type="_Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="_Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap>
<!-- 方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型 SELECT * FROM class WHERE c_id=1; SELECT * FROM teacher WHERE t_id=1 //1 是上一个查询得到的teacher_id的值 -->
<select id="getClass2" parameterType="int" resultMap="ClassResultMap2"> select * from class where c_id=#id </select> <resultMap type="_Classes" id="ClassResultMap2"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" select="getTeacher"> </association> </resultMap>
<select id="getTeacher" parameterType="int" resultType="_Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#id </select> |
5). 测试
@Test public void testOO() SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass", 1); System.out.println(c);
@Test public void testOO2() SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass2", 1); System.out.println(c);
|
6.2. 一对多关联
1). 提出需求
根据classId查询对应的班级信息,包括学生,老师
2). 创建表和数据:
CREATE TABLE student( s_id INT PRIMARY KEY AUTO_INCREMENT, s_name VARCHAR(20), class_id INT ); INSERT INTO student(s_name, class_id) VALUES('xs_A', 1); INSERT INTO student(s_name, class_id) VALUES('xs_B', 1); INSERT INTO student(s_name, class_id) VALUES('xs_C', 1); INSERT INTO student(s_name, class_id) VALUES('xs_D', 2); INSERT INTO student(s_name, class_id) VALUES('xs_E', 2); INSERT INTO student(s_name, class_id) VALUES('xs_F', 2);
|
3). 定义实体类:
public class Student private int id; private String name;
public class Classes private int id; private String name; private Teacher teacher; private List<Student> students;
|
4). 定义sql映射文件ClassMapper.xml
<!-- 方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集 SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1 --> <select id="getClass3" parameterType="int" resultMap="ClassResultMap3"> select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=#id </select> <resultMap type="_Classes" id="ClassResultMap3"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="_Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- ofType指定students集合中的对象类型 --> <collection property="students" ofType="_Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap>
<!-- 方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型 SELECT * FROM class WHERE c_id=1; SELECT * FROM teacher WHERE t_id=1 //1 是上一个查询得到的teacher_id的值 SELECT * FROM student WHERE class_id=1 //1是第一个查询得到的c_id字段的值 --> <select id="getClass4" parameterType="int" resultMap="ClassResultMap4"> select * from class where c_id=#id </select> <resultMap type="_Classes" id="ClassResultMap4"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="_Teacher" select="getTeacher2"></association> <collection property="students" ofType="_Student" column="c_id" select="getStudent"></collection> </resultMap>
<select id="getTeacher2" parameterType="int" resultType="_Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#id </select>
<select id="getStudent" parameterType="int" resultType="_Student"> SELECT s_id id, s_name name FROM student WHERE class_id=#id </select> |
5). 测试:
@Test public void testOM() SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass3", 1); System.out.println(c);
@Test public void testOM2() SqlSession sqlSession = factory.openSession(); Classes c = sqlSession.selectOne("com.atguigu.day03_mybatis.test5.OOMapper.getClass4", 1); System.out.println(c);
|
7. 动态SQL与模糊查询
7.1. 提出需求:
实现多条件查询用户(姓名模糊匹配, 年龄在指定的最小值到最大值之间)
7.2. 准备数据表和数据:
create table d_user( id int primary key auto_increment, name varchar(10), age int(3) );
insert into d_user(name,age) values('Tom',12); insert into d_user(name,age) values('Bob',13); insert into d_user(name,age) values('Jack',18); |
7.3. ConditionUser(查询条件实体类)
private String name; private int minAge; private int maxAge; |
7.4. User(表实体类)
private int id; private String name; private int age; |
7.5. 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.atguigu.day03_mybatis.test6.userMapper"> <select id="getUser" parameterType="com.atguigu.day03_mybatis.test6.ConditionUser" resultType="com.atguigu.day03_mybatis.test6.User"> select * from d_user where age>=#minAge and age<=#maxAge <if test='name!="%null%"'>and name like #name</if> </select> </mapper> |
7.6. UserTest(测试)
public class UserTest
public static void main(String[] args) throws IOException
Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sessionFactory.openSession();
String statement = "com.atguigu.day03_mybatis.test6.userMapper.getUser";
List<User> list = sqlSession.selectList(statement, new ConditionUser("%a%", 1, 12));
System.out.println(list);
|
MyBatis中可用的动态SQL标签
8.调用存储过程
8.1. 提出需求:
查询得到男性或女性的数量, 如果传入的是0就女性否则是男性