说明:本次使用的是mysql数据库。
create database mybatis;
use mybatis;
drop table if exists tb_user;
create table tb_user(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
gender char(1),
addr varchar(30)
);
insert into tb_user values (1,"zhangsan","123",'男','北京');
insert into tb_user values (2,"李四","234",'女','天津');
insert into tb_user values (3,"王五","11",'男','西安');
@Accessors(chain=true)
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private Long id;
private String username;
private String password;
private String gender;
private String addr;
}
<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.0modelVersion>
<groupId>com.ypygroupId>
<artifactId>mybatis-demoartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.23version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.21version>
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>
project>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.ypy.model.pojo"/>
typeAliases>
<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://localhost:3306/mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.ypy.mapper"/>
mappers>
configuration>
<configuration>
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>【%level】 %cyan(【%thread】) %boldGreen(%logger{15}) - %msg %npattern>
encoder>
appender>
<logger name="com.ypy.mapper.UserMapper" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
logger>
<root>
<level value="INFO">
<appender-ref ref="STDOUT"/>
level>
root>
configuration>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ypy.mapper.UserMapper">
<resultMap id="result-map" type="com.ypy.model.pojo.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="gender" property="gender" />
<result column="addr" property="addr"/>
resultMap>
<select id="selectAll" resultType="User">
select * from tb_user;
select>
<insert id="addOne" parameterType="User">
insert into tb_user values(id,username,password,gender,addr);
insert>
<select id="selectById" parameterType="int" resultMap="result-map">
select * from tb_user where id < #{id};
select>
<select id="selectByCondition" resultMap="result-map">
select *
from tb_user
where password = #{password}
and gender = #{gender}
and addr like #{addr}
select>
mapper>
@Mapper
public interface UserMapper {
List<User> selectAll();
void addOne(User user);
List<User> selectById(@Param("id") int id);
// 这里支持多参数,对象,Map形式传递参数
// List selectByCondition(@Param("gender") String gender,
// @Param("addr") String addr,@Param("password") String password);
// List selectByCondition(User user);
List<User> selectByCondition(Map map);
}
public class MybatisDemo {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
// 获取sqlSessionFactory
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
//获取sqlSession
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// List users = userMapper.selectAll();
// 条件查询
// List users = userMapper.selectByCondition(new User().setAddr("%北%").setPassword("123").setGender("男"));
Map<String, String> map = new HashMap<>();
map.put("addr","%北%");
map.put("password","123");
map.put("gender","男");
List<User> users = userMapper.selectByCondition(map);
// List user = userMapper.selectById(3);
System.out.println(users);
sqlSession.close();
}
}
10:43:56,346 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
10:43:56,346 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
10:43:56,347 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/D:/Application/WorkSpace/self-learn/base-learn/mybatis-demo/target/classes/logback.xml]
10:43:56,381 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
10:43:56,382 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
10:43:56,387 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [Console]
10:43:56,391 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
10:43:56,421 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.ypy.mapper.UserMapper] to DEBUG
10:43:56,421 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting additivity of logger [com.ypy.mapper.UserMapper] to false
10:43:56,421 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [Console] to Logger[com.ypy.mapper.UserMapper]
10:43:56,422 |-INFO in ch.qos.logback.classic.joran.action.LevelAction - ROOT level set to INFO
10:43:56,423 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@14:41 - no applicable action for [appender-ref], current ElementPath is [[configuration][root][level][appender-ref]]
10:43:56,423 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
10:43:56,424 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@3f49dace - Registering current configuration as safe fallback point
【DEBUG】 【main】 c.y.m.U.selectByCondition - ==> Preparing: select * from tb_user where password = ? and gender = ? and addr like ?
【DEBUG】 【main】 c.y.m.U.selectByCondition - ==> Parameters: 123(String), 男(String), %北%(String)
【DEBUG】 【main】 c.y.m.U.selectByCondition - <== Total: 1
[User(id=1, username=zhangsan, password=123, gender=男, addr=北京)]
Process finished with exit code 0
使用if和where标签解决。
<where>
<if test="name != null and name != ''">
name = #{name}
if>
where>
<select id="selectByConditionSingle" resultMap="brandResutlMap">
select * from tb_brand
where
<chose>
<when test="status!= null">
status = #{status}
when>
<when test="companyName != null and companyName != ''">
company_name like #{companyName}
when>
<otherwise>
1 = 1
otherwise>
chose>
select>
<insert id="addOne" parameterType="User">
insert into tb_user(username,password,gender,addr)
values(#{username},#{password},#{gender},#{addr});
insert>
插入数据后,数据库可能没有数据,原因可能是没有提交事务(数据库执行更新操作的操作,保证原子性)
void addOne(User user);
String resource = "mybatis-config.xml";
SqlSessionFactory sessionFactory = new
SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
//获取sqlSession
SqlSession sqlSession = sessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.addOne(new User().setPassword("9782").setGender("女").setAddr("上海")
.setUsername("赵烨"));
// 手动提交事务。也可以openSession的时候传入true,自动提交事务
sqlSession.commit();
扩展插入数据后,需要获取到记录的id
<insert useGeneratedKeys="true" keyProperty="id">
<update id="updateOne" parameterType="User">
update tb_user
set password = #{password},
username = #{username},
gender = #{gender},
addr = #{addr}
where id = #{id}
update>
long updateOne(User user);
<update id="updateCondition" parameterType="user">
update tb_user
<set>
<if test="password != null and password != ''">
password = #{password},
if>
<if test="username != null and username != ''">
username = #{username},
if>
<if test="gender != null and gender != ''">
gender = #{gender},
if>
<if test="addr != null and addr != ''">
addr = #{addr},
if>
set>
where id = #{id}
update>
long updateCondition(User user);
【DEBUG】 【main】 c.y.m.U.updateCondition - ==> Preparing: update tb_user SET password = ?, gender = ? where id = ?
【DEBUG】 【main】 c.y.m.U.updateCondition - ==> Parameters: 987987(String), 男(String), 4(Long)
【DEBUG】 【main】 c.y.m.U.updateCondition - <== Updates: 1
<delete id="deleteById">
delete from tb_user where id = #{id};
delete>
void deleteById(long id);
<delete id="deleteBatch">
delete from tb_user
where id in
<foreach collection="list" open="(" close=")" separator="," item="id">
#{id}
foreach>
delete>
void deleteBatch(List<Long> ids);
mybatis提供了ParamNameResolver类进行参数封装
思考:
如果接口方法传递的是一个map,key:user,value: new User(…);
但是sqlxml文件中如何获取这个user的属性呢?填充到占位符呢?