持久层:
框架:
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.10version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.31version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.20version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.26version>
dependency>
dependencies>
在resource下导入logback.xml配置
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %npattern>
encoder>
appender>
<logger name="com.xc" level = "DEBUG" additivity="false">
<appender-ref ref="Console" />
logger>
configuration>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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:///test?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="****"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="UserMapper.xml"/>
mappers>
configuration>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<select id="selectAll" resultType="com.xc.pojo.User">
select * from user
select>
mapper>
编码
package com.xc.pojo;
import lombok.Data;
/**
* @author xc
* @date 2023/5/30 18:21
*/
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String role;
}
public static void main(String[] args) throws IOException {
// 加载mybatis核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执行sql
List<User> userList = sqlSession.selectList("test.selectAll");
System.out.println(userList);
// 释放资源
sqlSession.close();
}
结果
目的
public interface UserMapper {
List<User> selectAll();
}
编码
public static void main(String[] args) throws IOException {
// 加载mybatis核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取UserMapper接口的代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 执行sql
List<User> userList = mapper.selectAll();
System.out.println(userList);
// 释放资源
sqlSession.close();
}
结果
注意:还可以使用包扫描的方式来加载sql映射文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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:///test?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="*****"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.xc.mapper"/>
mappers>
configuration>
官网:https://mybatis.org/mybatis-3/zh/configuration.html
environments
:配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment
typeAliases
:类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
配置各个标签时,需要遵守前后顺序
编写Mapper接口
public interface BrandMapper {
List<Brand> selectAll();
}
测试
package com.xc.testUser;
import com.xc.mapper.BrandMapper;
import com.xc.mapper.UserMapper;
import com.xc.pojo.Brand;
import com.xc.pojo.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.List;
/**
* @author xc
* @date 2023/5/30 18:24
*/
public class Mybatis {
SqlSession sqlSession;
BrandMapper mapper;
@Before
public void init() throws IOException {
// 加载mybatis核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession对象
sqlSession = sqlSessionFactory.openSession();
// 获取UserMapper接口的代理对象
mapper = sqlSession.getMapper(BrandMapper.class);
}
@Test
public void testSelectAll() {
List<Brand> brands = mapper.selectAll();
System.out.println(brands);
}
@After
public void end() {
// 释放资源
sqlSession.close();
}
}
结果
发现有的字段为null,因为字段名与数据库对应不上,解决办法:
或使用sql片段(不灵活)
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xc.mapper.BrandMapper">
<sql id="breand_cloumn">
id, brand_name as brandName, company_name as companyName, ordered, description,status
sql>
<select id="selectAll" resultType="com.xc.pojo.Brand">
select
<include refid="breand_cloumn"/>
from tb_brand
select>
mapper>
结果
使用resultMap
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xc.mapper.BrandMapper">
<resultMap id="brandResultMap" type="com.xc.pojo.Brand">
<result column="brand_name" property="brandName" />
<result column="company_name" property="companyName" />
resultMap>
<select id="selectAll" resultMap="brandResultMap">
select
*
from tb_brand
select>
mapper>
结果
定义Mapper接口
public interface BrandMapper {
List<Brand> selectAll();
Brand selectById(int id);
}
定义xml文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xc.mapper.BrandMapper">
<resultMap id="brandResultMap" type="com.xc.pojo.Brand">
<result column="brand_name" property="brandName" />
<result column="company_name" property="companyName" />
resultMap>
<select id="selectById" resultMap="brandResultMap">
select * from tb_brand where id = #{id}
select>
mapper>
查询
package com.xc.testUser;
import com.xc.mapper.BrandMapper;
import com.xc.mapper.UserMapper;
import com.xc.pojo.Brand;
import com.xc.pojo.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.List;
/**
* @author xc
* @date 2023/5/30 18:24
*/
public class Mybatis {
SqlSession sqlSession;
BrandMapper mapper;
@Before
public void init() throws IOException {
// 加载mybatis核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession对象
sqlSession = sqlSessionFactory.openSession();
// 获取UserMapper接口的代理对象
mapper = sqlSession.getMapper(BrandMapper.class);
}
@Test
public void testSelectById() {
Brand brand = mapper.selectById(1);
System.out.println(brand);
}
@After
public void end() {
// 释放资源
sqlSession.close();
}
}
结果
定义Mapper接口
public interface BrandMapper {
List<Brand> selectByCondition(@Param("status") int status, @Param("companyName") String companyName, @Param("brandName") String brandName);
List<Brand> selectByCondition(Brand brand);
List<Brand> selectByCondition(Map map);
}
编写映射文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xc.mapper.BrandMapper">
<resultMap id="brandResultMap" type="com.xc.pojo.Brand">
<result column="brand_name" property="brandName" />
<result column="company_name" property="companyName" />
resultMap>
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
where
status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName}
select>
mapper>
测试
package com.xc.testUser;
import com.xc.mapper.BrandMapper;
import com.xc.mapper.UserMapper;
import com.xc.pojo.Brand;
import com.xc.pojo.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.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author xc
* @date 2023/5/30 18:24
*/
public class Mybatis {
SqlSession sqlSession;
BrandMapper mapper;
@Before
public void init() throws IOException {
// 加载mybatis核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession对象
sqlSession = sqlSessionFactory.openSession();
// 获取UserMapper接口的代理对象
mapper = sqlSession.getMapper(BrandMapper.class);
}
@Test
public void testSelectByCondition() {
List<Brand> brands1 = mapper.selectByCondition(1,"%小%","%小米%");
Brand b = new Brand();
b.setStatus(1);
b.setBrandName("%华%");
b.setCompanyName("%华%");
List<Brand> brands2 = mapper.selectByCondition(b);
Map<String,Object> map = new HashMap<>();
map.put("status",0);
map.put("companyName","%三%");
map.put("brandName","%三%");
List<Brand> brands3 = mapper.selectByCondition(map);
System.out.println(brands1);
System.out.println("====================");
System.out.println(brands2);
System.out.println("====================");
System.out.println(brands3);
}
@After
public void end() {
// 释放资源
sqlSession.close();
}
}
结果
在xml中定义sql语句中添加if标签
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
where 1 = 1
<if test="status != null">
status = #{status}
if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
if>
<if test="brandName != null and brandName != '' ">
and brand_name like #{brandName}
if>
select>
优雅方式
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
<where>
<if test="status != null">
and status = #{status}
if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
if>
<if test="brandName != null and brandName != '' ">
and brand_name like #{brandName}
if>
where>
select>
多选一
Mapper接口
// 因为不知道要传那个参数,直接用Brand对象
List<Brand> selectByConditionSingle(Brand brand);
或者直接用where标签包裹
@Select("select * from tb_user where id = #{id}")
public User selectById(int id);
提示: