package com.czxy.ssm.domain;
import java.util.Date;
public class User {
private String uid;
private String username;
private String password;
private String name;
private String email;
private Date birthday;
private String sex;
private Integer state;
private String code;
@Override
public String toString() {
return "User{" +
"uid='" + uid + ''' +
", username='" + username + ''' +
", password='" + password + ''' +
", name='" + name + ''' +
", email='" + email + ''' +
", birthday=" + birthday +
", sex='" + sex + ''' +
", state=" + state +
", code='" + code + ''' +
'}';
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public User(String uid, String username, String password, String name, String email, Date birthday, String sex, Integer state, String code) {
this.uid = uid;
this.username = username;
this.password = password;
this.name = name;
this.email = email;
this.birthday = birthday;
this.sex = sex;
this.state = state;
this.code = code;
}
public User() {
}
}
1.5.2 编写Dao:UserMapper
之前的开发中我们编写的都是UserDao,在MyBatis将dao称为Mapper。
所以此后所有dao接口统一命名成Mapper。
在MyBatis只需要编写接口即可,实现类由MyBatis自动生成,并在测试程序时自动执行。
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
public List selectAll();
}
1.5.3 编写核心配置文件:SqlMapConfig.xml
配置文件名称:SqlMapConfig.xml
配置文件位置:src
配置文件内容:
1.5.4 测试类
package com.czxy.ssm.test;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test01_SelectAll {
public static void main(String[] args) throws IOException {
//1 加载配置文件
// 1.1 获得资源流
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
// 1.2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//2 获得会话(连接)
SqlSession session = factory.openSession();
//3获得功能接口
UserMapper userMapper = session.getMapper(UserMapper.class);
//4 调用功能
List userList = userMapper.selectAll();
//5 打印查询结果
for (User user : userList) {
System.out.println(user);
}
}
}
1.6 总结
到这里MyBatis的入门案例已经完成。我们总结一下:
编写SqlMapConfig.xml,用于配置数据源和需要加载的Mapper
编写UserMapper.java接口,用于执行方法与SQL语句的绑定
基本API使用,流程是:加载资源、获得工厂、获得会话、获得Mapper。
2. 基本操作:增删改查
2.1 模糊查询
功能接口中的方法
如果参数简单类型,sql语句需要使用value [不推荐]
@Select("select * from user where name like #{value}")
public List selectByName(String name);
如果使用@Param,可以进行相应的命名 【推荐】
@Select("select * from user where name like #{name}")
public List selectByName(@Param("name") String name);
测试类
package com.czxy.ssm.test;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test02_Like {
public static void main(String[] args) throws IOException {
//1 加载配置文件
// 1.1 获得资源流
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
// 1.2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//2 获得会话(连接)
SqlSession session = factory.openSession();
//3获得功能接口
UserMapper userMapper = session.getMapper(UserMapper.class);
//4 调用功能
List userList = userMapper.selectByName("%王%");
//5 打印查询结果
for (User user : userList) {
System.out.println(user);
}
}
}
2.2 插入数据
功能接口中的方法
@Insert("insert into user(uid, username, password, name, email, birthday, sex, state) values(#{uid},#{username},#{password},#{name},#{email},#{birthday},#{sex},#{state})")
public Integer insert(User user);
@Insert("update user set username=#{username}, password=#{password}, name=#{name}, email=#{email},birthday=#{birthday},sex=#{sex}, state=#{state} where uid=#{uid}")
public Integer update(User user);
测试类
package com.czxy.ssm.test;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
public class Test04_Update {
public static void main(String[] args) throws IOException {
//1 加载配置文件
// 1.1 获得资源流
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
// 1.2 获得工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//2 获得会话(连接)
SqlSession session = factory.openSession();
//3获得功能接口
UserMapper userMapper = session.getMapper(UserMapper.class);
//4 调用功能
User user = new User();
user.setUid("1");
user.setUsername("jack1");
user.setPassword("12341");
user.setName("杰克");
user.setEmail("itcast_lt@163.com");
user.setBirthday(new Date());
user.setSex("男");
user.setSex("0");
Integer result = userMapper.update(user);
System.out.println(result);
//5 提交资源
session.commit();
//6 释放资源
session.close();
}
}
2.4 删除数据
功能接口中的方法
@Delete("delete from user where uid = #{uid}")
public Integer deleteByPrimaryKey(@Param("uid") Integer uid);
@Select("select * from user")
@Results({
@Result(property = "uid", column = "uid", id = true),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password")
})
public List selectAll();
4.3.2 重复使用
语法
@Select(...)
@Results(id = "标识", value = {...})
public 返回值 方法名();
@Select(...)
@ResultMap("标识")
public 返回值 方法名2();
使用
@Select("select * from user")
@Results(id = "userResult", value = {
@Result(property = "uid", column = "uid", id = true),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password")
})
public List selectAll();
@Select("select * from user where uid = #{uid}")
@ResultMap("userResult")
public User selectById(@Param("uid") String uid);
@Select("select * from user where uid = #{uid}")
@ResultMap("userResult")
public User selectById(@Param("uid") String uid);
5.4.4 订单功能:通过id查询订单详情
@Select("select * from orders where oid = #{oid}")
@Results({
@Result(property="oid" , column="oid"),
@Result(property="ordertime" , column="ordertime"),
@Result(property="total" , column="total"),
@Result(property="state" , column="state"),
@Result(property="address" , column="address"),
@Result(property="name" , column="name"),
@Result(property="telephone" , column="telephone"),
@Result(property="uid" , column="uid"),
@Result(property="user" , one=@One(select="com.czxy.ssm.mapper.UserMapper.selectById") , column="uid"),
})
public Order selectById(@Param("oid") String id);
6.关联查询:多对多
6.1 学生和老师数据模型
6.1.1 表间关系
#老师表
CREATE TABLE teacher(
tid INT PRIMARY KEY,
NAME VARCHAR(50)
);
#学生表
CREATE TABLE student(
sid INT PRIMARY KEY,
NAME VARCHAR(50)
);
#中间表
CREATE TABLE teacher_student(
teacher_id INT ,
student_id INT,
CONSTRAINT ts_t_fk FOREIGN KEY (teacher_id) REFERENCES teacher(tid),
CONSTRAINT ts_s_fk FOREIGN KEY (student_id) REFERENCES student(sid)
);
INSERT INTO teacher VALUES (1,'肖老师');
INSERT INTO teacher VALUES (2,'马老师');
INSERT INTO student VALUES (1,'张三');
INSERT INTO student VALUES (2,'李四');
INSERT INTO student VALUES (3,'王五');
INSERT INTO teacher_student VALUES (1,1);
INSERT INTO teacher_student VALUES (1,2);
INSERT INTO teacher_student VALUES (1,3);
INSERT INTO teacher_student VALUES (2,1);
INSERT INTO teacher_student VALUES (2,2);
6.1.2 JavaBean及其关系
JavaBean:Student
package com.czxy.ssm.domain;
import java.util.ArrayList;
import java.util.List;
public class Teacher {
private Integer tid;
private String name;
private List studentList = new ArrayList<>();
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getStudentList() {
return studentList;
}
public void setStudentList(List studentList) {
this.studentList = studentList;
}
@Override
public String toString() {
return "Teacher{" +
"tid=" + tid +
", name='" + name + ''' +
", studentList=" + studentList +
'}';
}
}
6.2 多对多:老师–>学生
需要根据老师tid查询中间表中,对应的所有学生id
6.2.1 student 映射
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface StudentMapper {
@Select("select * from student s where s.sid in (select student_id from teacher_student where teacher_id = #{tid} )")
public Student findStudentByTeacherId(@Param("tid") Integer tid) throws Exception;
}
6.2.2 teacher 映射
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Teacher;
import org.apache.ibatis.annotations.*;
public interface TeacherMapper {
@Select("select * from teacher t where t.tid = #{tid}")
@Results({
@Result(property="tid" , column="tid"),
@Result(property="name" , column="name"),
@Result(property="studentList" , many=@Many(select="com.czxy.ssm.mapper.StudentMapper.findStudentByTeacherId") , column="tid"),
})
public Teacher selectById(@Param("tid") Integer tid);
}
package com.czxy.ssm.test;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.UserMapper;
import com.czxy.ssm.mapper.UserMapper2;
import com.czxy.ssm.utils.MyBatisUtils;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class Test13_Mapper {
@Test
public void testSelectByPrimaryKey() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
User user = userMapper2.selectByPrimaryKey("1");
System.out.println(user);
MyBatisUtils.commitAndclose();
}
}
8.4.2 查询所有
@Test
public void testSelectAll() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
List list = userMapper2.selectAll();
// 打印
list.forEach(System.out::println);
MyBatisUtils.commitAndclose();
}
8.4.3 添加
@Test
public void testInsert() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
User user = new User();
user.setUid("2");
user.setUsername("jack");
user.setPassword("1234");
user.setName("杰克");
user.setEmail("itcast_lt@163.com");
user.setBirthday(new Date());
user.setSex("男");
user.setSex("0");
int result = userMapper2.insert(user);
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
8.4.4 修改
@Test
public void testUpdate() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
User user = new User();
user.setUid("2");
user.setUsername("jack");
user.setPassword("1234");
user.setName("杰克");
user.setEmail("itcast_lt@163.com");
user.setBirthday(new Date());
user.setSex("男");
user.setSex("0");
int result = userMapper2.updateByPrimaryKey(user);
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
8.4.5 删除
@Test
public void testDelete() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
int result = userMapper2.deleteByPrimaryKey("2");
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
8.4.6 多条件查询
语法:
// 获得多条件对象
Example example = new Example(对象.class);
Example.Criteria criteria = example.createCriteria();
// 常见条件方法
andLike() //模糊查询
andEqualTo() //等值查询
andLessThanOrEqualTo() //<=查询
andGreaterThanOrEqualTo() //>=查询
andBetween() //区间查询
@Test
public void testCondition() {
UserMapper2 userMapper2 = MyBatisUtils.getMapper(UserMapper2.class);
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
criteria.andLike("name", "%王%");
criteria.andEqualTo("sex", "男");
List list = userMapper2.selectByExample(example);
for (User user : list) {
System.out.println(user);
}
MyBatisUtils.commitAndclose();
}
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.vo.UserVo;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
public User selectById(String uid);
public List selectAll();
public List selectByName(@Param("name") String name);
public Integer insert(User user);
public Integer updateByPrimaryKey(User user);
public Integer deleteByPrimaryKey(@Param("uid") String uid);
public List condition(UserVo userVo);
}
9.4.3 Mapper 映射文件
9.4.4 测试
package com.czxy.ssm.test;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.UserMapper;
import com.czxy.ssm.utils.MyBatisUtils;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class TestUserMapper {
@Test
public void testSelectById() {
UserMapper userMapper = MyBatisUtils.getMapper(UserMapper.class);
User user = userMapper.selectById("1");
System.out.println(user);
MyBatisUtils.commitAndclose();
}
@Test
public void testSelectAll() {
UserMapper UserMapper = MyBatisUtils.getMapper(UserMapper.class);
List list = UserMapper.selectAll();
// 打印
list.forEach(System.out::println);
MyBatisUtils.commitAndclose();
}
@Test
public void testSelectByName() {
UserMapper UserMapper = MyBatisUtils.getMapper(UserMapper.class);
List list = UserMapper.selectByName("%张%");
// 打印
list.forEach(System.out::println);
MyBatisUtils.commitAndclose();
}
@Test
public void testInsert() {
UserMapper UserMapper = MyBatisUtils.getMapper(UserMapper.class);
User user = new User();
user.setUid("2");
user.setUsername("jack");
user.setPassword("1234");
user.setName("杰克");
user.setEmail("itcast_lt@163.com");
user.setBirthday(new Date());
user.setSex("男");
user.setSex("0");
int result = UserMapper.insert(user);
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
@Test
public void testUpdate() {
UserMapper UserMapper = MyBatisUtils.getMapper(UserMapper.class);
User user = new User();
user.setUid("2");
user.setUsername("jack");
user.setPassword("1234");
user.setName("杰克");
user.setEmail("itcast_lt@163.com");
user.setBirthday(new Date());
user.setSex("男");
user.setSex("0");
int result = UserMapper.updateByPrimaryKey(user);
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
@Test
public void testDelete() {
UserMapper UserMapper = MyBatisUtils.getMapper(UserMapper.class);
int result = UserMapper.deleteByPrimaryKey("2");
// 打印
System.out.println(result);
MyBatisUtils.commitAndclose();
}
}
uid, username, password, name, email, birthday, sex, state
select from user
9.6 关系映射:一对多
9.6.1 mapper接口
UserMapper,已有
public interface UserMapper {
public User selectById(String uid);
}
OrderMapper
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Order;
import org.apache.ibatis.annotations.Param;
public interface OrderMapper {
public Order findOrdersByUserId(@Param("uid") Integer uid) ;
}
9.6.2 Mapper 映射文件
OrdersMapper.xml
select * from orders where uid = #{uid}
UserMapper.xml
select * from user where uid = #{id}
9.6.3 核心配置文件
9.6.4 测试
public class TestUserMapper {
@Test
public void testSelectById() {
UserMapper userMapper = MyBatisUtils.getMapper(UserMapper.class);
User user = userMapper.selectById("u001");
System.out.println(user);
MyBatisUtils.commitAndclose();
}
}
9.7 关系映射:多对一
9.7.1 mapper接口
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Order;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface OrderMapper {
public Order selectById(@Param("oid") String oid);
}
9.7.2 映射文件:OrdersMapper.xml
select * from orders where oid = #{oid}
9.7.3 测试类
package com.czxy.ssm.test;
import com.czxy.ssm.domain.Order;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.OrderMapper;
import com.czxy.ssm.mapper.UserMapper;
import com.czxy.ssm.utils.MyBatisUtils;
import com.czxy.ssm.vo.UserVo;
import org.junit.Test;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class TestOrderMapper {
@Test
public void testSelectById() {
OrderMapper orderMapper = MyBatisUtils.getMapper(OrderMapper.class);
Order order = orderMapper.selectById("x001");
System.out.println(order);
MyBatisUtils.commitAndclose();
}
}
-3-mapper.dtd">
select * from orders where uid = #{uid}
UserMapper.xml
select * from user where uid = #{id}
9.6.3 核心配置文件
9.6.4 测试
public class TestUserMapper {
@Test
public void testSelectById() {
UserMapper userMapper = MyBatisUtils.getMapper(UserMapper.class);
User user = userMapper.selectById("u001");
System.out.println(user);
MyBatisUtils.commitAndclose();
}
}
9.7 关系映射:多对一
9.7.1 mapper接口
package com.czxy.ssm.mapper;
import com.czxy.ssm.domain.Order;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface OrderMapper {
public Order selectById(@Param("oid") String oid);
}
9.7.2 映射文件:OrdersMapper.xml
select * from orders where oid = #{oid}
9.7.3 测试类
package com.czxy.ssm.test;
import com.czxy.ssm.domain.Order;
import com.czxy.ssm.domain.User;
import com.czxy.ssm.mapper.OrderMapper;
import com.czxy.ssm.mapper.UserMapper;
import com.czxy.ssm.utils.MyBatisUtils;
import com.czxy.ssm.vo.UserVo;
import org.junit.Test;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class TestOrderMapper {
@Test
public void testSelectById() {
OrderMapper orderMapper = MyBatisUtils.getMapper(OrderMapper.class);
Order order = orderMapper.selectById("x001");
System.out.println(order);
MyBatisUtils.commitAndclose();
}
}