1.导包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
2.配置
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>
<properties resource="com/bailiban/mybatis/jdbc.properties"></properties>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- <typeAliases>-->
<!-- 给类娶一个别名,短一点好写-->
<!-- <typeAlias type="com.bailiban.mybatis.model.User" alias="User"/>-->
<!-- 指定包名,包名下的类,都可以简写类名-->
<!-- <package name="com.bailiban.model"/>-->
<!-- </typeAliases>-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/bailiban/mybatis/UserMapper.xml"/>
<mapper resource="com/bailiban/mybatis/AdviceMapper.xml"/>
</mappers>
</configuration>
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.cj.jdbc.Driver
3.动态sql使用示例
trim标签(推荐使用)
<update id="updateUser">
update user
<trim prefix="set" suffixOverrides=",">
<if test="name!=null">
name =#{name},
</if>
</trim>
where id=#{id}
</update>
where标签
<!--<select id="getMyAdvices" resultType="com.bailiban.model.MyAdvice">
select * from advice
<where>
<if test="name!=null">
name=#{name}
</if>
<if test="money!=null">
money >= #{money}
</if>
<if test="id!=null">
id=#{id}
</if>
</where>
</select>-->
其他标签去官网看吧,,,
4.复杂操作练习(one:一对一,many:一对多)
User.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class User2 {
private Integer id;
private String name;
private MyAdvice myAdvice;
private List<MyAdvice> advices;
}
MyAdvice.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class MyAdvice {
private String name;
private Double money;
private String miaoshu;
private Integer id;
private Integer uId;
}
UserMapper.java
使用注解的one、many
public interface UserMapper {
User2 getUser(int id);
int addUsers(List<User2> userList);
int insertUser(User2 user);
int updateUser(User2 user);
int delUser(int id);
@Results(id = "iUser",value = {
@Result(column = "id",property = "id",id = true),
@Result(column = "name",property = "name"),
@Result(property = "myAdvice",column = "id",one =
@One(select = "com.bailiban.mybatis.AdviceMapper.getAdvice")),
@Result(property = "advices",column = "id",many =
@Many(select = "com.bailiban.mybatis.AdviceMapper.getMyAdvices2"))
})
@Select("select * from user where id=#{id}")
User2 getUser2(int id);
}
UserMapper.xml
使用xml,one对应的标签<association>
,many对应标签<collection>
<?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.bailiban.mybatis.UserMapper">
<cache readOnly="true"/>
<resultMap id="myUser" type="com.bailiban.model.User2">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="myAdvice" autoMapping="true">
<result property="name" column="aname"/>
<result property="uId" column="u_id"/>
</association>
<collection property="advices" ofType="com.bailiban.model.MyAdvice">
<result property="name" column="aname"/>
<result property="uId" column="u_id"/>
</collection>
</resultMap>
<select id="getUser" resultMap="myUser">
select u.*,a.name aname,a.money,a.`describe`,a.u_id from user u join advice a on u.id=a.id where u.id = #{id}
</select>
<insert id="addUsers">
insert into user (name) values
<foreach collection="list" item="user" separator=",">
(#{user.name})
</foreach>
</insert>
<insert id="insertUser">
insert into user (id,name) values (#{id},#{name})
</insert>
<update id="updateUser">
update user
<trim prefix="set" suffixOverrides=",">
<if test="name!=null">
name =#{name},
</if>
</trim>
where id=#{id}
</update>
<delete id="delUser">
delete from user where id=#{id}
</delete>
</mapper>
5. 缓存
一级缓存
session级别
生效时间:默认就有
失效时间:修改操作、session关闭
二级缓存
也叫命名空间缓存,跨session作用范围大
生效时间:提交、session关闭
失效时间:修改操作
顺序:先查二级缓存,再查一级缓存,再查数据库。
开启二级缓存的配置
mybatis-config.xml
<setting name="cacheEnabled" value="true"/>
UserMapper.xml的mapper标签里
<cache readOnly="true"/>
readOnly=“true”,无反序列化,速度快,安全性低;
readOnly=“false”,缓存数据是序列化的,再次访问时需要反序列化,安全性高(避免同一对象被多方修改);
6.线程安全
package com.bailiban.threadsafe;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadTest {
private int count;
private AtomicInteger integer;
private ThreadLocal<Integer> number;
public ThreadTest(int count,AtomicInteger integer,ThreadLocal<Integer> number) {
this.count = count;
this.integer = integer;
this.number = number;
}
public void test(){
int i=10000;
number.set(0);
while (i-->0){
count++;
integer.incrementAndGet();
number.set(number.get()+1);
}
System.out.println("[ThreadLocal number = ]"+number.get());
}
public static void main(String[] args) throws InterruptedException {
ThreadLocal<Integer> number=new ThreadLocal<Integer>();
number.set(0);
ThreadTest test=new ThreadTest(0,new AtomicInteger(0),number);
Thread[] ts=new Thread[10];
for (int i=0;i<10;i++){
ts[i]=new MyThread(test);
ts[i].start();
}
for (int i=0;i<10;i++){
ts[i].join();
}
System.out.println("[test.count = ]"+test.count);
System.out.println("[test.integer = ]"+test.integer.get());
System.out.println("[test.number = ]"+test.number.get());
}
}
一般可使用synchronized解决。
基础类型,可以使用原子变量解决。
spring mybatis使用ThreadLocal<Integer>
解决。