文章目录
- bean
-
- Clazz.java
- Student.java
- Teacher.java
- User.java
- config
-
- mapper
-
- ClazzMapper.java
- StudentMapper.java
- UserMapper.java
- resources
-
- log4j.properties
- mybatis-config.xml
- resources.mapper
-
- ClazzMapper.xml
- StudentMapper.xml
- UserMapper.xml
- test.java.net.sherry.mybatis.bean
-
- test.java.net.sherry.mybatis.mapper
-
- TestClazzMapper.java
- TestStudentMapper.java
- TestuserMapper.java
- TestUserMapperNew.java
bean
Clazz.java
package net.sherry.mybatis.bean;
import java.util.List;
public class Clazz {
private int id;
private String name;
private Teacher teacher;
private List<Student> students;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Clazz{" +
"id=" + id +
", name='" + name + '\'' +
", teacher=" + teacher.getName() +
", students=" + students +
'}';
}
}
Student.java
package net.sherry.mybatis.bean;
public class Student {
private int id;
private String name;
private String gender;
private int age;
private Clazz clazz;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", clazz=" + clazz.getName() +
'}';
}
}
Teacher.java
package net.sherry.mybatis.bean;
public class Teacher {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
User.java
package net.sherry.mybatis.bean;
public class User {
private int id;
private String name;
private int age;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
config
MyBatisConfig.java
package net.sherry.mybatis.config;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;
public class MyBatisConfig {
public static Configuration getConfiguration() {
Configuration configuration = null;
TransactionFactory transactionFactory = new JdbcTransactionFactory();
DataSource dataSource = new PooledDataSource(
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/testdb?useSSL=false",
"root",
"111111"
);
Environment environment = new Environment("development", transactionFactory, dataSource);
configuration = new Configuration(environment);
return configuration;
}
}
mapper
ClazzMapper.java
package net.sherry.mybatis.mapper;
import net.sherry.mybatis.bean.Clazz;
import java.util.List;
public interface ClazzMapper {
Clazz findById(int id);
List<Clazz> findAll();
}
StudentMapper.java
package net.sherry.mybatis.mapper;
import net.sherry.mybatis.bean.Student;
import java.util.List;
import java.util.Map;
public interface StudentMapper {
List<Student> findByCondition(Map<String, Object> condition);
}
UserMapper.java
package net.sherry.mybatis.mapper;
import net.sherry.mybatis.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
User findById(int id);
List<User> findAll();
List<User> findByName(String name);
int insert(User user);
int update(User user);
int deleteById(int id);
}
resources
log4j.properties
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/mybatis.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="net.sherry.mybatis.bean.User" alias="User"/>
<typeAlias type="net.sherry.mybatis.bean.Clazz" alias="Clazz"/>
<typeAlias type="net.sherry.mybatis.bean.Teacher" alias="Teacher"/>
<typeAlias type="net.sherry.mybatis.bean.Student" alias="Student"/>
typeAliases>
<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/testdb?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
<mapper resource="mapper/ClazzMapper.xml"/>
<mapper resource="mapper/StudentMapper.xml"/>
mappers>
configuration>
resources.mapper
ClazzMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.sherry.mybatis.mapper.ClazzMapper">
<select id="findById" parameterType="int" resultMap="clazzResultMap">
SELECT * FROM t_teacher
INNER JOIN t_class ON t_class.teacher_id = t_teacher.t_id
INNER JOIN t_student ON t_class.c_id = t_student.class_id
WHERE c_id = #{id};
select>
<resultMap id="clazzResultMap" type="Clazz">
<result property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="Teacher">
<result property="id" column="t_id"/>
<result property="name" column="t_name"/>
association>
<collection property="students" ofType="Student">
<result property="id" column="s_id"/>
<result property="name" column="s_name"/>
<result property="gender" column="s_gender"/>
<result property="age" column="s_age"/>
<association property="clazz" column="class_id" javaType="Clazz">
<result property="name" column="c_name"/>
association>
collection>
resultMap>
<select id="findAll" resultMap="clazzResultMap2">
SELECT * FROM t_class;
select>
<resultMap id="clazzResultMap2" type="Clazz">
<result property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="Teacher" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="Teacher">
SELECT t_id id, t_name name FROM t_teacher WHERE t_id = #{id};
select>
mapper>
StudentMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.sherry.mybatis.mapper.StudentMapper">
<select id="findByCondition" parameterType="java.util.Map" resultMap="studentResultMap">
SELECT * FROM t_student
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="name != null">
s_name Like CONCAT(#{name},'%')
if>
<if test="gender != null">
AND s_gender = #{gender}
if>
<if test="age != null">
AND s_age = #{age}
if>
trim>
select>
<resultMap id="studentResultMap" type="Student">
<result column="s_id" property="id"/>
<result column="s_name" property="name"/>
<result column="s_gender" property="gender"/>
<result column="s_age" property="age"/>
<association property="clazz" column="class_id" javaType="Clazz" select="getClazz"/>
resultMap>
<select id="getClazz" resultType="Clazz">
SELECT c_id id, c_name name FROM t_class WHERE c_id = #{id};
select>
mapper>
UserMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.sherry.mybatis.mapper.UserMapper">
<resultMap id="userMap" type="User">
<result column="id" jdbcType="INTEGER" property="id" javaType="int"/>
<result column="name" jdbcType="VARCHAR" property="name" javaType="String"/>
<result column="age" jdbcType="INTEGER" property="age" javaType="int"/>
<result column="address" jdbcType="VARCHAR" property="address" javaType="String"/>
resultMap>
<select id="findById" parameterType="int" resultType="User">
SELECT * FROM t_user WHERE id = #{id};
select>
<select id="findByName" resultType="User">
select * from t_user where name like concat(#{name}, "%");
select>
<select id="findAll" resultMap="userMap">
SELECT * FROM t_user;
select>
<insert id="insert" parameterType="User"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO t_user(name, age, address)
VALUES(#{name}, #{age}, #{address})
insert>
<update id="update" parameterType="User">
UPDATE t_user SET name = #{name}, age = #{age},
address = #{address} WHERE id = #{id};
update>
<delete id="deleteById" parameterType="int">
DELETE FROM t_user WHERE id = #{id};
delete>
mapper>
test.java.net.sherry.mybatis.bean
TestUserOperation.java
package net.sherry.mybatis.bean;
import net.sherry.mybatis.bean.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class TestUserOperation {
private SqlSession sqlSession;
@Before
public void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession();
System.out.println("SQL会话创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindById() {
int id = 1;
User user = sqlSession.selectOne("net.sherry.mybatis.mapper.UserMapper.findById", id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test
public void testFindAll() {
List<User> users = sqlSession.selectList("net.sherry.mybatis.mapper.UserMapper.findAll");
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
sqlSession.close();
System.out.println("SQL会话已经关闭~");
}
}
test.java.net.sherry.mybatis.mapper
TestClazzMapper.java
package net.sherry.mybatis.mapper;
import net.sherry.mybatis.bean.Clazz;
import net.sherry.mybatis.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.Null;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class TestClazzMapper {
private SqlSession sqlSession;
private ClazzMapper clazzMapper;
@Before
public void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession();
clazzMapper = sqlSession.getMapper(ClazzMapper.class);
System.out.println("SQL回话创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindById() {
int id = 1;
Clazz clazz = clazzMapper.findById(id);
if (clazz != null) {
System.out.println(clazz);
System.out.println("班级编号[" + id + "]的学生:");
List<Student> students = clazz.getStudents();
students.forEach(student -> System.out.println(student));
}else {
System.out.println("班级编号[" + id + "]的班级不存在~");
}
}
@Test
public void testFindAll() {
List<Clazz> clazzes = clazzMapper.findAll();
clazzes.forEach(clazz -> System.out.println(clazz));
}
@After
public void destroy() {
sqlSession.close();
System.out.println("SQL会话关闭~");
}
}
TestStudentMapper.java
package net.sherry.mybatis.mapper;
import net.sherry.mybatis.bean.Student;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class TestStudentMapper {
private SqlSession sqlSession;
private StudentMapper studentMapper;
@Before
public void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession();
studentMapper = sqlSession.getMapper(StudentMapper.class);
System.out.println("创建SQL成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindByCondition(){
HashMap<String, Object> condition = new HashMap<String, Object>();
condition.put("gender", "女");
condition.put("age", 19);
condition.put("name", "吴");
List<Student> students = studentMapper.findByCondition(condition);
if (students.size() > 0){
students.forEach(student -> System.out.println(student));
}else {
System.out.println("没有找到~");
}
}
@After
public void destroy() {
sqlSession.close();
System.out.println("已关闭SQL会话~");
}
}
TestuserMapper.java
package net.sherry.mybatis.mapper;
import net.sherry.mybatis.bean.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class TestUserMapper {
private SqlSession sqlSession;
private UserMapper userMapper;
@Before
public void init() {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println("SQL会话创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindById() {
int id = 1;
User user = userMapper.findById(id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test
public void testFindByName(){
String name = String.valueOf('王');
List<User> users = userMapper.findByName(name);
users.forEach(user -> System.out.println(user));
}
@Test
public void testFindAll() {
List<User> users = userMapper.findAll();
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
sqlSession.close();
System.out.println("SQL会话已经关闭~");
}
@Test
public void testInsert(){
User user = new User();
user.setName("王雨涵");
user.setAge(30);
user.setAddress("古蔺县郎酒厂");
int count = userMapper.insert(user);
sqlSession.commit();
if (count > 0){
System.out.println("纪录插入成功!");
System.out.println("插入新的纪录:" +user);
}else {
System.out.println("纪录插入失败!");
}
}
@Test
public void testUpdate(){
User user = userMapper.findById(4);
System.out.println("更新前的纪录: " + userMapper.findById(4));
user.setName("萌萌哒");
user.setAge(30);
user.setAddress("北京朝阳区北苑路6号楼");
userMapper.update(user);
sqlSession.commit();
System.out.println("更新成功!");
System.out.println("更新后的记录:"+ userMapper.findById(4));
}
@Test
public void testDeleteById(){
int id = 4;
User user = userMapper.findById(id);
System.out.println("待删除的记录:" + user);
userMapper.deleteById(id);
sqlSession.commit();
System.out.println("编号为[" + id + "]的记录删除成功!");
user = userMapper.findById(id);
if (user != null){
System.out.println(user);
}else {
System.out.println("编号为[" + id + "] 的用户未找到");
}
}
}
TestUserMapperNew.java
package net.sherry.mybatis.mapper;
import net.sherry.mybatis.bean.User;
import net.sherry.mybatis.config.MyBatisConfig;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class TestUserMapperNew {
private SqlSession sqlSession;
private UserMapper userMapper;
@Before
public void init() {
Configuration configuration = MyBatisConfig.getConfiguration();
configuration.addMapper(UserMapper.class);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configuration);
sqlSession = factory.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println("SQL会话创建成功~");
}
@Test
public void testFindById() {
int id = 1;
User user = userMapper.findById(id);
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test
public void testFindAll() {
List<User> users = userMapper.findAll();
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
sqlSession.close();
System.out.println("SQL会话已经关闭~");
}
}