标签:publickey 增删改 没有 bug 规则 constrain incr deb utf8
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
jdbc.url=jdbc:mysql://192.168.134.100:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=123456
<?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">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-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="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
package com.sunxiaping.domain;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
public Employee() {
}
public Employee(Integer id, String lastName, String email, String gender) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName=‘" + lastName + ‘\‘‘ +
", email=‘" + email + ‘\‘‘ +
", gender=‘" + gender + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
/**
* 根据id查询员工的信息
*
* @param id
* @return
*/
Employee findById(Integer id);
/**
* 增加员工信息
*
* @param employee
*/
void addEmp(Employee employee);
/**
* 修改员工信息
*
* @param employee
*/
void updateEmp(Employee employee);
/**
* 根据id删除员工信息
*
* @param id
*/
void deleteEmpById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findById" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{id,jdbcType=INTEGER}
</select>
<insert id="addEmp">
INSERT INTO employee (last_name,email,gender)
VALUES (#{lastName,jdbcType=VARCHAR},#{email,jdbcType=VARCHAR},#{gender,jdbcType=VARCHAR})
</insert>
<update id="updateEmp">
UPDATE employee
SET last_name = #{lastName,jdbcType=VARCHAR},email = #{email,jdbcType=VARCHAR},gender=#{gender,jdbcType=VARCHAR}
WHERE id = #{id,jdbcType=INTEGER}
</update>
<delete id="deleteEmpById">
DELETE FROM employee
WHERE id = #{id,jdbcType=INTEGER}
</delete>
</mapper>
<?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>
<properties resource="db.properties"></properties>
<settings>
<!-- 开启自动驼峰命名规则映射 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 使用${}引入db.properties属性文件中的内容 -->
<property name="driver" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.sunxiaping.mapper"/>
</mappers>
</configuration>
package com.sunxiaping;
import com.sunxiaping.domain.Employee;
import com.sunxiaping.mapper.EmployeeMapper;
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.InputStream;
public class EmployeeTest {
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
EmployeeMapper employeeMapper = null;
@Before
public void before() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
}
@After
public void after() {
if (null != sqlSession) {
sqlSession.close();
}
}
@Test
public void testFindById() {
Employee employee = employeeMapper.findById(1);
System.out.println("employee = " + employee);
}
@Test
public void testAddEmp() {
Employee employee = new Employee();
employee.setEmail("jerry@qq.com");
employee.setGender("男");
employee.setLastName("jerry");
employeeMapper.addEmp(employee);
}
@Test
public void testUpdateEmp(){
Employee employee = employeeMapper.findById(2);
employee.setGender("女");
employeeMapper.updateEmp(employee);
}
@Test
public void testDeleteEmpById(){
employeeMapper.deleteEmpById(2);
}
}
MySQL等数据库支持自增主键,自增主键的值是通过statement.getGenerateKeys()方法获取的。
通过使用useGeneratedKeys="true"
开启自增主键获取主键值的策略。
通过使用keyProperty="id"
指定对应的主键属性,Mybatis获取主键值以后,将这个值封装给JavaBean的哪个属性。
示例:
<?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.sunxiaping.mapper.EmployeeMapper">
<!--
MySQL支持自增主键,自增主键值的获取,Mybatis是利用statement.getGeneratedKeys()
useGeneratedKeys="true":使用自增主键获取主键值策略
keyProperty="id":指定对应的主键属性,Mybatis获取主键值以后,将这个值封装给JavaBean的哪个属性
-->
<insert id="addEmp" useGeneratedKeys="true" keyProperty="id" parameterType="com.sunxiaping.domain.Employee">
INSERT INTO employee (last_name,email,gender)
VALUES (#{lastName,jdbcType=VARCHAR},#{email,jdbcType=VARCHAR},#{gender,jdbcType=VARCHAR})
</insert>
</mapper>
Oracle不支持自增主键,Oracle是使用序列来模拟自增的。
每次插入的数据的主键都是从序列中拿到的值。
示例:
<?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.sunxiaping.mapper.EmployeeMapper">
<!--
Oracle不支持自增主键,Oracle是使用序列来模拟自增的。
每次插入的数据的主键都是从序列中拿到的值。
-->
<insert id="addEmp" useGeneratedKeys="true" keyProperty="id" parameterType="com.sunxiaping.domain.Employee">
<!--
插入时的主键是从序列中拿到的
keyProperty:查询的主键封装给JavaBean的哪个属性
order:
- BEFORE:当前的SQL在插入SQL之前运行
- 运行顺序:先运行selectKey中的SQL语句,查询出id,然后将id封装给JavaBean中的id属性,在运行插入SQL的时候,就可以取出id属性对应的值
- AFTER: 先运行插入SQL,再运行当前的SQL
- 运行顺序:先运行插入的SQL(会从序列中取出新值作为id),再运行selectKey查询id,然后将id封装给JavaBean的id属性,并发情况下可能有问题。
resultType:查出的数据的返回值类型
-->
<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Integer">
<!--
编写查询主键的SQL语句
-->
SELECT employee_seq.nextval FROM dual
</selectKey>
INSERT INTO employee (id,last_name,email,gender)
VALUES (#{id,jdbcType=INTEGER},#{lastName,jdbcType=VARCHAR},#{email,jdbcType=VARCHAR},#{gender,jdbcType=VARCHAR})
</insert>
</mapper>
<?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.sunxiaping.mapper.EmployeeMapper">
<!--
Oracle不支持自增主键,Oracle是使用序列来模拟自增的。
每次插入的数据的主键都是从序列中拿到的值。
-->
<insert id="addEmp" useGeneratedKeys="true" keyProperty="id" parameterType="com.sunxiaping.domain.Employee">
<!--
插入时的主键是从序列中拿到的
keyProperty:查询的主键封装给JavaBean的哪个属性
order:
- BEFORE:当前的SQL在插入SQL之前运行
- 运行顺序:先运行selectKey中的SQL语句,查询出id,然后将id封装给JavaBean中的id属性,在运行插入SQL的时候,就可以取出id属性对应的值
- AFTER: 先运行插入SQL,再运行当前的SQL
- 运行顺序:先运行插入的SQL(会从序列中取出新值作为id),再运行selectKey查询id,然后将id封装给JavaBean的id属性,并发情况下可能有问题。
resultType:查出的数据的返回值类型
-->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
<!--
编写查询主键的SQL语句
-->
SELECT employee_seq.currval FROM dual
</selectKey>
INSERT INTO employee (id,last_name,email,gender)
VALUES (employee_seq.nextval},#{lastName,jdbcType=VARCHAR},#{email,jdbcType=VARCHAR},#{gender,jdbcType=VARCHAR})
</insert>
</mapper>
Mybatis不需要经过任何处理,Mybatis可以直接使用#{参数名}
取出参数值。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
/**
* 根据id查询员工的信息
*
* @param id
* @return
*/
Employee findById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findById" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{abc,jdbcType=INTEGER}
</select>
</mapper>
任意多个参数,都会被Mybatis重新包装成一个Map传入。Map中的key就是param1,param2,…,value是传入的参数值。
#{}
就是从map中获取指定的key的值。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
/**
* 根据id和lastName查询员工信息
*
* @param id
* @param lastName
* @return
*/
Employee findByIdAndLastName(Integer id, String lastName);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findByIdAndLastName" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{param1,jdbcType=INTEGER} AND last_name = #{param2,jdbcType=VARCHAR}
</select>
</mapper>
当多个参数的时候,可以使用@Param
注解明确指定Mybatis中传入参数Map中的key,Map中的key就是使用@Param
注解指定的值,value就是传入的参数值。
#{指定的key}
就可以取出对应的参数值。
示例:
Employee.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import org.apache.ibatis.annotations.Param;
public interface EmployeeMapper {
/**
* 根据id和lastName查询员工信息
*
* @param id
* @param lastName
* @return
*/
Employee findByIdAndLastName(@Param("id") Integer id,@Param("lastName") String lastName);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findByIdAndLastName" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{id,jdbcType=INTEGER} AND last_name = #{lastName,jdbcType=VARCHAR}
</select>
</mapper>
如果多个参数正好是业务逻辑的数据模型,我们就可以直接传入POJO。#{属性名}
取出传入POJO的属性值。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
Employee findByPOJO(Employee employee);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findByPOJO" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{id,jdbcType=INTEGER} AND last_name = #{lastName,jdbcType=VARCHAR}
</select>
</mapper>
如果多个参数不是业务模型的数据,没有对应的POJO,不经常使用,为了方便,我们可以传入Map。
#{key}
取出传入map中对应的值。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import java.util.Map;
public interface EmployeeMapper {
Employee findByMap(Map<String, Object> map);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findByMap" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{id,jdbcType=INTEGER} AND last_name = #{lastName,jdbcType=VARCHAR}
</select>
</mapper>
如果多个参数不是业务模型中的数据,但是经常使用,推荐编写一个TO(Transfer Object)数据传输对象。
示例:
Page.java
package com.sunxiaping.to;
/**
* 分页的参数
*/
public class Page {
/**
* 每页显示条数
*/
private Integer pageSize;
/**
* 起始页码
*/
private Integer pageNum;
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
@Override
public String toString() {
return "Page{" +
"pageSize=" + pageSize +
", pageNum=" + pageNum +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import com.sunxiaping.to.Page;
import java.util.List;
public interface EmployeeMapper {
List<Employee> findByPage(Page page);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findByPage" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
LIMIT #{pageNum},#{pageSize}
</select>
</mapper>
如果传入的参数是Collection类型(List类型、Set类型)或数组类型,那么Mybatis会针对这些类型进行特殊处理:如果是Collection类型,那么Mybatis内部封装参数的Map的key就是collection;如果是List类型,那么Mybatis内部封装参数的Map的key可以是list;而如果是数组类型,Mybatis内部封装参数的Map的key是array。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import java.util.List;
import java.util.Set;
public interface EmployeeMapper {
List<Employee> findBySet(Set<Integer> id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findBySet" resultType="com.sunxiaping.domain.Employee">
SELECT id,last_name as lastName,email,gender
FROM employee
WHERE id = #{collection}
</select>
</mapper>
#{}
获取参数的值,预编译到SQL中,安全。
${}
获取参数的值,拼接到SQL中,有SQL注入问题。
注意:
大多数情况下,我们取参数的值的时候使用
#{}
。原生JDBC不支持占位符的地方,我们就可以使用
${}
。
- 比如:排序
Order BY ${name}
- 比如:财务系统在设计之初按照年份分表,查询的时候应该这样写:
SELECT * FROM ${year}_salary WHERE xxx;
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import java.util.Map;
public interface EmployeeMapper {
Employee findByMap(Map<String,Object> map);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findByMap" resultType="com.sunxiaping.domain.Employee" parameterType="java.util.Map">
SELECT id,last_name as lastName,email,gender
FROM ${tableName}
WHERE id = #{id}
</select>
</mapper>
package com.sunxiaping;
import com.sunxiaping.domain.Employee;
import com.sunxiaping.mapper.EmployeeMapper;
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.InputStream;
import java.util.HashMap;
import java.util.Map;
public class EmployeeTest {
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
EmployeeMapper employeeMapper = null;
@Before
public void before() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession(true);
employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
}
@After
public void after() {
if (null != sqlSession) {
sqlSession.close();
}
}
@Test
public void testFindById() {
Map<String, Object> map = new HashMap<>();
map.put("id",1);
map.put("tableName","employee");
Employee employee = employeeMapper.findByMap(map);
System.out.println("employee = " + employee);
}
}
Mybatis在参数位置支持如下的属性:
在某种特定的条件下,jdbcType通常需要被设置。
示例:修改Mybatis对Oracle的NULL值的默认处理
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
int addEmp(Employee employee);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<insert id="addEmp" useGeneratedKeys="true" keyProperty="id" parameterType="com.sunxiaping.domain.Employee">
<selectKey>
SELECT employee_seq.nextval FROM dual
</selectKey>
INSERT INTO employee (id,last_name,email,gender)
<!--
在Oracle数据库中,如果是null值,需要设置jdbcType=NULL
-->
VALUES (#{id,jdbcType=INTEGER},#{lastName,jdbcType=VARCHAR},#{email,jdbcType=NULL},#{gender,jdbcType=VARCHAR})
</insert>
</mapper>
对于resultType来说,如果返回的是一个集合,需要写集合中的类型。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import java.util.List;
public interface EmployeeMapper {
List<Employee> findByGender(String gender);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<!--
resultType:如果返回的是一个集合,需要写集合里面的类型
-->
<select id="findByGender" resultType="com.sunxiaping.domain.Employee">
SELECT * FROM employee
WHERE gender = #{gender,jdbcType=VARCHAR}
</select>
</mapper>
返回一条记录封装Map,key就是列名,值就是对应的值。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import java.util.Map;
public interface EmployeeMapper {
Map<String, Object> findById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findById" resultType="java.util.Map">
SELECT * FROM employee
WHERE id = #{id,jdbcType=INTEGER}
</select>
</mapper>
返回多条记录将其封装为Map<主键类型,对象类型>,key是这条记录的主键,值是这条记录。
示例:
EmployeeMapper.java
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import org.apache.ibatis.annotations.MapKey;
import java.util.Map;
public interface EmployeeMapper {
@MapKey("id")
Map<Integer, Employee> findById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<select id="findById" resultType="java.util.Map">
SELECT id,last_name as lastName,gender,email FROM employee
WHERE id = #{id,jdbcType=INTEGER}
</select>
</mapper>
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
Employee findById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<!--
resultMap 自定义关系结果映射规则
id:唯一方便引用的id
type:自定义规则的JavaBean类型
-->
<resultMap id="emp" type="com.sunxiaping.domain.Employee">
<!--
id:指定主键列的封装规则
column:指定哪一列
property:指定column对应的JavaBean属性
-->
<id property="id" column="id"/>
<!--
result:定义普通列的封装规则
column:指定哪一列
property:指定column对应的JavaBean属性
-->
<result property="lastName" column="last_name"/>
<!-- 其它不指定的列会自动封装 -->
<result property="email" column="email"/>
<result property="gender" column="gender"/>
</resultMap>
<select id="findById" resultMap="emp">
SELECT * FROM employee
WHERE id = #{id,jdbcType=INTEGER}
</select>
</mapper>
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `department` VALUES (1, ‘开发部‘);
INSERT INTO `department` VALUES (2, ‘测试部‘);
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`department_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `fk_department_id`(`department_id`) USING BTREE,
CONSTRAINT `fk_department_id` FOREIGN KEY (`department_id`) REFERENCES `department` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `employee` VALUES (1, ‘tom‘, ‘男‘, ‘tom@qq.com‘, 1);
INSERT INTO `employee` VALUES (2, ‘aa‘, ‘女‘, NULL, 2);
package com.sunxiaping.domain;
public class Department {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName=‘" + lastName + ‘\‘‘ +
", email=‘" + email + ‘\‘‘ +
", gender=‘" + gender + ‘\‘‘ +
", department=" + department +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
Employee findEmpAndDeptById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<resultMap id="emp" type="com.sunxiaping.domain.Employee">
<id property="id" column="id"/>
<result property="lastName" column="last_name"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<result property="department.id" column="did"/>
<result property="department.name" column="dept_name"/>
</resultMap>
<select id="findEmpAndDeptById" resultMap="emp">
SELECT e.id as id,e.last_name as last_name,e.gender as gender,e.email as email,d.id as did,d.name as dept_name
FROM employee e INNER JOIN department d
ON e.department_id = d.id
WHERE e.id = #{id,jdbcType=INTEGER}
</select>
</mapper>
package com.sunxiaping.domain;
public class Department {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName=‘" + lastName + ‘\‘‘ +
", email=‘" + email + ‘\‘‘ +
", gender=‘" + gender + ‘\‘‘ +
", department=" + department +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
Employee findEmpAndDeptById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<resultMap id="emp" type="com.sunxiaping.domain.Employee">
<id property="id" column="id"/>
<result property="lastName" column="last_name"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<!--
association:可以指定联合的JavaBean对象
property:指定哪个属性是联合的对象
javaType:指定联合对象的类型
-->
<association property="department" javaType="com.sunxiaping.domain.Department">
<id property="id" column="did"/>
<id property="name" column="dept_name"/>
</association>
</resultMap>
<select id="findEmpAndDeptById" resultMap="emp">
SELECT e.id as id,e.last_name as last_name,e.gender as gender,e.email as email,d.id as did,d.name as dept_name
FROM employee e INNER JOIN department d
ON e.department_id = d.id
WHERE e.id = #{id,jdbcType=INTEGER}
</select>
</mapper>
package com.sunxiaping.domain;
public class Department {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName=‘" + lastName + ‘\‘‘ +
", email=‘" + email + ‘\‘‘ +
", gender=‘" + gender + ‘\‘‘ +
", department=" + department +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Department;
public interface DepartmentMapper {
Department findById(Integer id);
}
<?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.sunxiaping.mapper.DepartmentMapper">
<select id="findById" resultType="com.sunxiaping.domain.Department">
SELECT *
FROM department
WHERE id = #{id,jdbcType=INTEGER}
</select>
</mapper>
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
Employee findEmpAndDeptById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<resultMap id="emp" type="com.sunxiaping.domain.Employee">
<!--
分步查询:
①按照员工id查询员工信息
②根据查询员工信息中的department_id去部门表中查询部门信息
③部门设置到员工中
-->
<id property="id" column="id"/>
<result property="lastName" column="last_name"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<!--
association 定义关联对象的封装规则
property:关联对象的属性
select:表明当前属性是调用select查询的结果
column:指定将那一列的值传给这个方法
流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的关联对象的属性
-->
<association property="department" select="com.sunxiaping.mapper.DepartmentMapper.findById" column="did" />
</resultMap>
<select id="findEmpAndDeptById" resultMap="emp">
SELECT e.id as id,e.last_name as last_name,e.gender as gender,e.email as email,e.department_id as did
FROM employee e
WHERE e.id = #{id,jdbcType=INTEGER}
</select>
</mapper>
分步查询中使用延迟加载:需要在mybatis-config.xml中配置如下的全局设置
<settings> <!-- 开启自动驼峰命名规则映射 --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 开启对jdbcType的NULL的支持 --> <setting name="jdbcTypeForNull" value="NULL"/> <!-- 开启延迟加载 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 开启按需加载 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>
package com.sunxiaping.domain;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName=‘" + lastName + ‘\‘‘ +
", email=‘" + email + ‘\‘‘ +
", gender=‘" + gender + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import java.util.List;
public class Department {
private Integer id;
private String name;
private List<Employee> employees;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
", employees=" + employees +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Department;
public interface DepartmentMapper {
Department findById(Integer id);
}
<?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.sunxiaping.mapper.DepartmentMapper">
<resultMap id="dept" type="com.sunxiaping.domain.Department">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!--
collection 定义关联集合类型的属性的封装规则
ofType 定义集合中元素的类型
-->
<collection property="employees" ofType="com.sunxiaping.domain.Employee">
<!-- 定义这个集合中元素的封装规则 -->
<id property="id" column="eid"/>
<result property="lastName" column="lastName"/>
<result property="gender" column="gender"/>
<result property="email" column="email"/>
</collection>
</resultMap>
<select id="findById" resultMap="dept">
SELECT d.id as id,d.name as name,e.id as eid,e.last_name as lastName,e.email as email,e.gender as gender
FROM department d
INNER JOIN employee e
ON d.id = e.department_id
WHERE d.id = #{id,jdbcType=INTEGER}
</select>
</mapper>
package com.sunxiaping.domain;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName=‘" + lastName + ‘\‘‘ +
", email=‘" + email + ‘\‘‘ +
", gender=‘" + gender + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import java.util.List;
public class Department {
private Integer id;
private String name;
private List<Employee> employees;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
", employees=" + employees +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
import java.util.List;
public interface EmployeeMapper {
List<Employee> findByDepatmentId(Integer departmentId);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<resultMap id="emp" type="com.sunxiaping.domain.Employee">
<id property="id" column="id"/>
<result property="lastName" column="last_name"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
</resultMap>
<select id="findByDepatmentId" resultMap="emp">
SELECT e.id as id,e.last_name as last_name,e.gender as gender,e.email as email,e.department_id as did
FROM employee e
WHERE e.department_id = #{departmentId,jdbcType=INTEGER}
</select>
</mapper>
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Department;
public interface DepartmentMapper {
Department findById(Integer id);
}
<?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.sunxiaping.mapper.DepartmentMapper">
<resultMap id="dept" type="com.sunxiaping.domain.Department">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="employees" select="com.sunxiaping.mapper.EmployeeMapper.findByDepatmentId" column="{id}">
</collection>
</resultMap>
<select id="findById" resultMap="dept">
SELECT d.id as id,d.name as name
FROM department d
WHERE d.id = #{id,jdbcType=INTEGER}
</select>
</mapper>
有的时候,分步查询不是传递一个值,而是传递多列值,这个时候我们需要使用{key1=column1,key2=clomn2…}的形式来多列值封装map传递。
示例:
DepartmentMapper.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.sunxiaping.mapper.DepartmentMapper">
<resultMap id="dept" type="com.sunxiaping.domain.Department">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="employees" select="com.sunxiaping.mapper.EmployeeMapper.findByDepatmentId" column="{departmentId=id}">
</collection>
</resultMap>
<select id="findById" resultMap="dept">
SELECT d.id as id,d.name as name
FROM department d
WHERE d.id = #{id,jdbcType=INTEGER}
</select>
</mapper>
Mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为。
示例:判断Employee,如果查出的是女生,就把部门信息查询出来,否则不查询;如果查询出来的是男生,就把last_name这一列的值赋值给email
Department.java
package com.sunxiaping.domain;
public class Department {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import org.apache.ibatis.type.Alias;
@Alias("emp")
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName=‘" + lastName + ‘\‘‘ +
", email=‘" + email + ‘\‘‘ +
", gender=‘" + gender + ‘\‘‘ +
", department=" + department +
‘}‘;
}
}
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Department;
public interface DepartmentMapper {
Department findById(Integer id);
}
<?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.sunxiaping.mapper.DepartmentMapper">
<resultMap id="dept" type="com.sunxiaping.domain.Department">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
<select id="findById" resultMap="dept">
SELECT d.id as id,d.name as name
FROM department d
WHERE d.id = #{id,jdbcType=INTEGER}
</select>
</mapper>
package com.sunxiaping.mapper;
import com.sunxiaping.domain.Employee;
public interface EmployeeMapper {
Employee findById(Integer id);
}
<?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.sunxiaping.mapper.EmployeeMapper">
<resultMap id="emp" type="com.sunxiaping.domain.Employee">
<id property="id" column="id"/>
<result property="lastName" column="last_name"/>
<result property="email" column="email"/>
<result property="gender" column="gender"/>
<!--
discriminator 鉴别器
column:指定要判断的列名
javaType:指定要判断的列对应的java类型
-->
<discriminator javaType="string" column="gender">
<case value="女" resultType="com.sunxiaping.domain.Employee">
<association property="department" javaType="java.lang.Integer" select="com.sunxiaping.mapper.DepartmentMapper.findById" column="did"/>
</case>
<case value="男" resultType="com.sunxiaping.domain.Employee">
<id property="id" column="id"/>
<result property="lastName" column="last_name"/>
<result property="email" column="last_name"/>
<result property="gender" column="gender"/>
</case>
</discriminator>
</resultMap>
<select id="findById" resultMap="emp">
SELECT e.id as id,e.last_name as last_name,e.gender as gender,e.email as email,e.department_id as did
FROM employee e
WHERE e.department_id = #{departmentId,jdbcType=INTEGER}
</select>
</mapper>
标签:publickey 增删改 没有 bug 规则 constrain incr deb utf8
原文地址:https://www.cnblogs.com/xuweiweiwoaini/p/13660075.html