Mybatis框架的构建(IDEA)
选择maven项目
修改设置
在设置中添加自定义代码模板
开始写代码
动态SQL语句的示例:
pom文件:
<?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>com.qcby</groupId><artifactId>MyBatisDemoTest</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!--mybatis核心包--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><!--mysql驱动包--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><!-- 单元测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version></dependency><!-- 日志 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies></project>
实体层:
package com.qcby.entity;import java.util.Date;/**对应数据库当中的user表*/
public class User {private Integer id;private String username;private Date birthday;private String sex;private String address;private String password;private Integer pagesize;private Integer pageStart;public User() {}public User(String username, Date birthday, String sex, String address) {this.username = username;this.birthday = birthday;this.sex = sex;this.address = address;}public Integer getPagesize() {return pagesize;}public void setPagesize(Integer pagesize) {this.pagesize = pagesize;}public Integer getPageStart() {return pageStart;}public void setPageStart(Integer pageStart) {this.pageStart = pageStart;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}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 String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", birthday=" + birthday +", sex='" + sex + '\'' +", address='" + address + '\'' +", password='" + password + '\'' +'}';}
}
dao层:
package com.qcby.dao;import com.qcby.entity.User;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface UserDao {List<User> findUser(User user);int update(User user);List<User> selectUserByChoose(User user);List<User> selectUserByUsernameAndSex(User user);int trimUpdate(User user);int deleteMoreByArray(@Param("ids") Integer[] ids);int insertMoreByList(@Param("users") List<User> users);
}
SqlMapConfig:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><!--设置Mybatis输出日志--><!--logImpl: 表示对日志的控制--><!--STDOUT_LOGGING: 将日志输出到控制台上--><setting name="logImpl" value="STDOUT_LOGGING"/></settings><environments default="mysql"><environment id="mysql"><!--配置事务的类型,使用本地事务策略--><transactionManager type="JDBC"></transactionManager><!--是否使用连接池 POOLED表示使用链接池,UNPOOLED表示不使用连接池--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><mapper resource="mapper/UserMapper.xml"></mapper><mapper resource="mapper/StudentMapper.xml"></mapper><mapper resource="mapper/PersonMapper.xml"></mapper><mapper resource="mapper/TeacherMapper.xml"></mapper></mappers>
</configuration>
Test文件:
import com.qcby.dao.UserDao;
import com.qcby.entity.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.InputStream;
import java.util.Date;
import java.util.Arrays;
import java.util.List;public class UserTest {private InputStream in = null;private SqlSession session = null;private UserDao mapper = null;@Before //前置通知, 在方法执行之前执行public void init() throws IOException {//加载主配置文件,目的是为了构建SqlSessionFactory对象in = Resources.getResourceAsStream("SqlMapConfig.xml");//创建SqlSessionFactory对象SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);//通过SqlSessionFactory工厂对象创建SqlSesssion对象session = factory.openSession();//通过Session创建UserDao接口代理对象mapper = session.getMapper(UserDao.class);}@After //@After: 后置通知, 在方法执行之后执行 。public void destory() throws IOException {//释放资源session.close();in.close();}@Testpublic void findUser(){User user = new User();//user.setUsername("熊大");user.setAddress("上海");user.setPassword("123");List<User> users = mapper.findUser(user);for (User user1: users) {System.out.println(user1.toString());}}@Testpublic void insert(){User user = new User();user.setUsername("sssssss");user.setId(1);mapper.update(user);session.commit();}@Testpublic void trimUpdate(){User user = new User();user.setUsername("sssssss");user.setId(1);mapper.trimUpdate(user);session.commit();}@Testpublic void selectUserByChoose(){User user1 = new User();user1.setId(1);//user1.setUsername("admin");List<User> users = mapper.selectUserByChoose(user1);for (User user: users) {System.out.println(user.toString());}}@Testpublic void selectUserByUsernameAndSex(){User user = new User();user.setUsername("熊大");// user.setAddress("上海");user.setPassword("123");List<User> users = mapper.selectUserByUsernameAndSex(user);for (User user1: users) {System.out.println(user1.toString());}}@Testpublic void deleteMoreByArray(){Integer[] integer = new Integer[]{8,9,10,11};mapper.deleteMoreByArray(integer);session.commit();}@Testpublic void insertMoreByList(){User user1 = new User("小赵",new Date(),"男","保定");User user2 = new User("小张",new Date(),"男","保定");User user3 = new User("小李",new Date(),"男","保定");List<User> users = Arrays.asList(user1,user2,user3);mapper.insertMoreByList(users);session.commit();}
}
Mapper文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcby.dao.UserDao"><!--where if--><select id="findUser" resultType="com.qcby.entity.User" parameterType="com.qcby.entity.User">select * from user<where><if test="username != null and username != ''">username = #{username}</if><if test="birthday != null">and birthday = #{birthday}</if><if test="address != null and address != ''">and address = #{address}</if><if test="password != null and password != ''">and password = #{password}</if></where></select><update id="update" parameterType="com.qcby.entity.User" >update user<set><if test="username != null and username != ''">username = #{username},</if><if test="birthday != null">birthday = #{birthday},</if><if test="address != null and address != ''">address = #{address},</if><if test="password != null and password != ''">password = #{password},</if></set>where id = #{id}</update><select id="selectUserByChoose" resultType="com.qcby.entity.User"parameterType="com.qcby.entity.User">select * from user<where><choose><when test="username != null and username != ''">username = #{username}</when><when test="birthday != null">and birthday=#{birthday}</when><otherwise>and id=#{id}</otherwise></choose></where></select><select id="selectUserByUsernameAndSex" parameterType="com.qcby.entity.User"resultType="com.qcby.entity.User">select * from user<trim prefix="where" prefixOverrides="and | or"><if test="username != null and username != ''">username = #{username}</if><if test="birthday != null">and birthday = #{birthday}</if><if test="address != null and address != ''">and address = #{address}</if><if test="password != null and password != ''">and password = #{password}</if></trim></select><update id="trimUpdate" parameterType="com.qcby.entity.User">update user<trim prefix="set" suffixOverrides=","><if test="username != null and username != ''">username = #{username},</if><if test="birthday != null">birthday = #{birthday},</if><if test="address != null and address != ''">address = #{address},</if><if test="password != null and password != ''">password = #{password},</if></trim>where id = #{id}</update><!--delete from user where id in (1,2,3,4,5); --><delete id="deleteMoreByArray">delete from user where id in<foreach collection="ids" item="id" separator="," open="(" close=")">#{id}</foreach></delete><!-- collection:当前要循环的数组或者集合 --><!-- item: 我们指定要循环的数组的每一个元素 --><!-- separator:每一个元素应该用什么来做分割 --><!-- open:当前循环是以什么开始 --><!-- close:当前循环是以什么结束 --><!--insert into 表名 (字段) values (值),(值)--><insert id="insertMoreByList" >insert into user(username,birthday,sex,address) values<foreach collection="users" item="user" separator=",">(#{user.username},#{user.birthday},#{user.sex},#{user.address})</foreach></insert>
</mapper>