spring+mybatis
整体结构
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.mythsky</groupId> <artifactId>spring-boot-mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-boot-mybatis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.8-dmr</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
log4j.properties
log4j.rootLogger=ERROR,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis-config.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.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.31.146:3306/mydb"/> <property name="username" value="root"/> <property name="password" value="password"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
User
package org.mythsky.mybatis; public class User { private Integer id; private String name; private Integer sex; private Integer age; public User(String name, Integer sex, Integer age) { this.name = name; this.sex = sex; this.age = age; } 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 Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
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="org.mythsky.mybatis"> <insert id="save" parameterType="org.mythsky.mybatis.User" useGeneratedKeys="true"> INSERT INTO person(name,sex,age) VALUES (#{name},#{sex},#{age}) </insert> </mapper>
这里需要注意的是Mapper上需要指定namespace
MyBatisTest
package org.mythsky.mybatis; 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; public class MyBatisTest { public static void main(String[] args) throws IOException { InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession session=factory.openSession(); User user=new User("admin",1,18); session.insert("save",user); session.commit(); session.close(); } }
运行Test
查看数据库
select
修改MybatisTest
InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession session=factory.openSession(); User user=session.selectOne("org.mythsky.mybatisdemo.domain.selectUser",1); System.out.println(user); session.commit(); session.close();
修改UserMapper
<select id="selectUser" parameterType="int" resultType="org.mythsky.mybatisdemo.domain.User"> SELECT * FROM person WHERE id=#{id} </select>
此时运行会报错,因为User没有4个参数的构造函数,修改User,添加带id的构造函数
public User(Integer id, String name, Integer sex, Integer age) { this.id = id; this.name = name; this.sex = sex; this.age = age; }
再次运行即可
update
UserMapper新增配置
<update id="updateUser" parameterType="org.mythsky.mybatisdemo.domain.User"> UPDATE person SET name=#{name},sex=#{sex},age=#{age} WHERE id=#{id} </update>
Test代码更新
User user=session.selectOne("org.mythsky.mybatisdemo.domain.selectUser",1); user.setName("tom"); session.update("org.mythsky.mybatisdemo.domain.updateUser",user);
运行后查看数据库
delete
UserMapper更新
<delete id="deleteUser" parameterType="int"> DELETE FROM person WHERE id=#{id} </delete>
测试更新
session.delete("org.mythsky.mybatisdemo.domain.deleteUser",2);
运行后查看数据库
ResultMap
添加配置
<select id="selectUserMap" resultType="map"> select * from person </select>
测试
List<Map<String,Object>> list=session.selectList("org.mythsky.mybatisdemo.domain.selectUserMap"); for(Map<String,Object> row:list){ System.out.println(row); }
结果
添加两张表
CREATE table tb_clazz(id int PRIMARY KEY auto_increment,code varchar(18)); INSERT into tb_clazz(code) VALUES('c0001'); INSERT into tb_clazz(code) VALUES('c0002'); CREATE TABLE tb_student(id int PRIMARY KEY auto_increment,name varchar(18),sex char(3),age int,clazz_id int); insert into tb_student(name,sex,age,clazz_id) values ('jack','男',22,1); insert into tb_student(name,sex,age,clazz_id) values ('rose','女',18,1); insert into tb_student(name,sex,age,clazz_id) values ('tom','男',25,2); insert into tb_student(name,sex,age,clazz_id) values ('jerry','女',20,2);
Clazz
package org.mythsky.mybatisdemo.domain; public class Clazz { private Integer id; private String code; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
Student
package org.mythsky.mybatisdemo.domain; public class Student { private Integer id; private String name; private String sex; private Integer age; private Clazz clazz; 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 String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Clazz getClazz() { return clazz; } public void setClazz(Clazz clazz) { this.clazz = clazz; } }
UserMapper
<resultMap id="studentResultMap" type="org.mythsky.mybatisdemo.domain.Student"> <id property="id" column="id"></id> <result property="name" column="name"></result> <result property="sex" column="sex"></result> <result property="age" column="age"></result> <association property="clazz" column="clazz_id" javaType="org.mythsky.mybatisdemo.domain.Clazz" select="selectClazzWithId"></association> </resultMap> <select id="selectClazzWithId" resultType="org.mythsky.mybatisdemo.domain.Clazz"> select * from tb_clazz WHERE id=#{id}; </select> <select id="selectStudent" resultMap="studentResultMap"> select * from tb_student; </select>
Test
List<Student> list=session.selectList("org.mythsky.mybatisdemo.domain.selectStudent"); for(Student student:list){ System.out.println(student); }
运行
更新Clazz
private List<Student> students; public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; }
更新mapper
<resultMap id="clazzResultMap" type="org.mythsky.mybatisdemo.domain.Clazz"> <id property="id" column="id"></id> <result property="code" column="code"></result> <collection property="students" javaType="ArrayList" column="id" ofType="org.mythsky.mybatisdemo.domain.Student" select="selectStudentWithId"></collection> </resultMap> <select id="selectStudentWithId" resultType="org.mythsky.mybatisdemo.domain.Student"> SELECT * from tb_student where clazz_id=#{id} </select> <select id="selectClazz" resultMap="clazzResultMap"> select * from tb_clazz; </select>
更新测试
List<Clazz> list=session.selectList("org.mythsky.mybatisdemo.domain.selectClazz"); for(Clazz clazz:list){ System.out.println(clazz); List<Student> students=clazz.getStudents(); for(Student student:students){ System.out.println(student.getId()+" "+student.getName()+" "+student.getSex()+" "+student.getAge()); } }
运行结果