在mybatis中
package mybatis.chap01;
import java.util.Date;
import org.apache.ibatis.type.Alias;
@Alias("Stu")
public class Student {
private Integer s_id;
private String name;
private String email;
private Date dob;
public Student() {
}
public Student(Integer id,String name, String email,Date dob) {
this.s_id=id;
this.name=name;
this.email=email;
this.dob=dob;
}
public Integer getId() {
return s_id;
}
public void setId(Integer id) {
this.s_id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDate() {
return dob;
}
public void setDate(Date dob) {
this.dob = dob;
}
@Override
public String toString() {
return "Student [s_id=" + s_id + ", name=" + name + ", email=" + email + ", dob=" + dob + "]";
}
}
package mybatis.chap01;
import java.util.HashMap;
import java.util.List;
public interface StudentMapper {
void insertStudent(Student student);
Student findStudentByid(Integer id);
void updateStudent(Student student);
int deleteStudent();
List<Student> findAllStudent();
HashMap<String, Object> findById(Integer id);
List<String> findAllName();
List<HashMap<String, Object>> find();
}
配置文件jdbc.properties
driver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@localhost:1521:XE
user = xi
passwd =oracle
<?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="mybatis.chap01.StudentMapper">
<!-- 对于有别名的(数据库内定义的名字与proj类属性名不一致的)使用resultMap+id-->
<resultMap type="Stu" id="StudentResult">
<id property="s_id" column="id"/>
<id property="name" column="name"/>
<id property="email" column="email"/>
<id property="dob" column="dob"/>
</resultMap>
<!--插入 -->
<insert id="insertStudent" parameterType="Stu">
<selectKey keyProperty="s_id" resultType="int" order="BEFORE">
select stud_id.nextval from dual
</selectKey>
insert into stud(id,name,email,dob)
values(#{s_id},#{name},#{email},#{dob})
</insert>
<!-- resultType是指返回类型,写全限定类名,或者在上面写别名,在mybatis-config.xml中配置别名 -->
<select id="findStudentByid" parameterType="int" resultType="Stu">
select id as s_id,name,email from stud where id = #{id}
</select>
<update id="updateStudent" parameterType="Stu">
update stud set name = #{name},email = #{email}
where id = #{id}
</update>
<delete id="deleteStudent">
delete from stud
</delete>
<select id="findAllStudent" resultMap="StudentResult">
select * from stud
</select>
<select id="findById" parameterType="int" resultType="map" >
select * from stud where id=#{id}
</select>
<select id="findAllName" resultType="map">
SELECT name FROM stud
</select>
<select id="find" resultType="map" >
select * from stud
</select>
</mapper>
<?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>
<!-- 读取jdbc.properties文件中的数据key value 形式 -->
<properties resource="jdbc.properties">
<property name="user" value="xi"/>
<property name="passwd" value="oracle"/>
</properties>
<!-- <settings>
<setting name="" value=""/>
</settings> -->
<!-- 类型别名 -->
<typeAliases>
<!-- 注册一个简写的类名,可以在其他地方引用 -->
<typeAlias type="mybatis.chap01.Student" alias="Stu" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${passwd}" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- mapper中有三种方法,但还是用这种,或者下面的package类型引入文件 -->
<mapper resource="mybatis/chap01/StudentMapper.xml"/>
<!-- 这种方法可以引用该包下的所有Mapper.xml文件 -->
<!--<package name="com.mapper"/> -->
</mappers>
</configuration>
工厂类
package mybatis.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory() {
if(sqlSessionFactory == null) {
InputStream is = null;
try {
is = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}
return sqlSessionFactory;
}
//手动提交
public static SqlSession openSession() {
return openSession(false);
}
//自动提交
public static SqlSession openSession(boolean autoCommit) {
return getSqlSessionFactory().openSession(autoCommit);
}
}
测试类
package mybatis.test;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.hamcrest.core.Is;
import org.junit.Test;
import mybatis.chap01.Student;
import mybatis.chap01.StudentMapper;
import mybatis.chap02.Address;
import mybatis.chap02.Tutor;
import mybatis.chap04.PicMapper;
import mybatis.chap04.UserPic;
import mybatis.util.MybatisSqlSessionFactory;
import servlet.chap02.User;
public class MybatisTest {
@Test
public void student_test() {
/* * 1.读取mybatis-config.xml配置文件
* 2.创建sqlSessionFactory工厂
* 3.创建sqlSession对象
* 4.sqlSession对象调用getMapper方法
* 传入StudentMapper接口的类对象
* 返回StudentMapper接口的实现类
* 5.执行接口中的方法*/
//MybatisSqlSessionFactory factory=(MybatisSqlSessionFactory) MybatisSqlSessionFactory.getSqlSessionFactory();
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
//Student s = new Student(1,"tom","[email protected]",new Date());
StudentMapper mapper = session.getMapper(StudentMapper.class);
//mapper.insertStudent(s);
//session.commit();
Student s = mapper.findStudentByid(15);
System.out.println(s);
//session.insert("mybatis.chap01.StudentMapper.insertStudent",s);
//session.commit();
session.selectOne("mybatis.chap01.StudentMapper.findStudentByid",15);
}catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void student_update(){
SqlSession session = MybatisSqlSessionFactory.openSession(true);
/*StudentMapper mapper = session.getMapper(StudentMapper.class);
int count = mapper.deleteStudent();
System.out.println("删除"+count+"行");*/
Student s = new Student();
s.setId(11);
s.setName("jack");
s.setEmail("[email protected]");
//mapper.updateStudent(s);
session.update("mybatis.chap01.StudentMapper.updateStudent",s);
//session.delete("mybatis.chap01.StudentMapper.deleteStudent");
}
@Test
public void Student_select() {
SqlSession session = MybatisSqlSessionFactory.openSession(true);
StudentMapper mapper = session.getMapper(StudentMapper.class);
/* List list=mapper.findAllStudent();
for(Student s:list) {
System.out.println(s);
}
HashMap map=mapper.findById(15);
Set set=map.keySet();
for(String key:set) {
System.out.println(key+" "+map.get(key));
}
List list=mapper.findAllName();
for(String key:list) {
System.out.println(key);
}*/
List<HashMap<String, Object>> list=mapper.find();
for(HashMap<String, Object> map:list) {
Set<Map.Entry<String, Object>> set=map.entrySet();
for(Map.Entry<String, Object> entry:set) {
}
System.out.println();
}
}
@Test
public void One2One() {
SqlSession session = MybatisSqlSessionFactory.openSession(true);
mybatis.chap02.One2One mapper = session.getMapper(mybatis.chap02.One2One.class);
Address address=mapper.findAddressById(1);
System.out.println(address);
mybatis.chap02.Student student=mapper.selectStudentWithAddress(1);
System.out.println(student);
}
@Test
public void One2many() {
SqlSession session = MybatisSqlSessionFactory.openSession(true);
mybatis.chap02.One2many mapper = session.getMapper(mybatis.chap02.One2many.class);
Address address=mapper.findAddressById(1);
System.out.println(address);
Tutor tutor=mapper.findTutorById(1);
System.out.println(tutor);
}
@Test
public void special_test() {
//图片
SqlSession session = MybatisSqlSessionFactory.openSession(true);
PicMapper mapper = session.getMapper(PicMapper.class);
File file =new File("src/1.jpg");
byte[] pic=null;
try {
InputStream inputStream=new FileInputStream(file);
pic=new byte[inputStream.available()];
inputStream.read(pic);
inputStream.close();
String name="rose";
String bio="自拍照";
UserPic userPic=new UserPic(1,name,pic,bio);
mapper.insertUserPic(userPic);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UserPic userPicById = mapper.getUserPicById(1);
System.out.println(userPicById);
}
}
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
–针对于查询语句为in
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
—针对于大量重复使用的大量查询字段
—选择,按某一个取,取到一个就结束。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
一级缓存正常开启。
一级缓存是会话级别,需要在同一个会话中才可以使用,一旦关闭会话,则会重新去数据库查。
mapper.find();
//第二次从缓存中拿
mapper.find();
mapper.find();
close();
//第二次继续数据库中拿
mapper.find();
查询会去缓存中查询,如果存在,就去拿,不会去数据库查了,
如果开启二级缓存
先去二级缓存,再到一级缓存,最后数据库。
mybatis-config.xml
<settings>
<!--保证缓存开启-->
<setting name="cacheEnabled" value="true"/>
</settings>
mapping.xml
2. size(引用数目)属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。
3. readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。 因此这些对象不能被修改。这就提供了可观的性能提升。而可读写的缓存会(通过序列化)返回缓存对象的拷贝。 速度上会慢一些,但是更安全,因此默认值是 false。
–提示 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新。
可用的清除策略有:
LRU
– 最近最少使用:移除最长时间不被使用的对象。
FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。
SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。
WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
<!--开启二级缓存-->
<cache/>
序列化–对于数据进行序列化后可以保证持久,缓存到二级缓存中
public class Teacher implements Serializable{
测试
@Test
public void m6(){
//实现了对于二级缓存的测试
SqlSessionFactory sqlSession=MybatisSqlSessionFactory.getSqlSessionFactory();
SqlSessionFactory sqlSession1=MybatisSqlSessionFactory.getSqlSessionFactory();
SqlSession session=sqlSession.openSession();
SqlSession session1=sqlSession1.openSession();
//crtl+alt+v可以补全类型
TeacherMapper mapper = session.getMapper(TeacherMapper.class);
TeacherMapper mapper1 = session1.getMapper(TeacherMapper.class);
mapper.selectTeacherbyidandname3(1,"找钱");
session.close();
mapper1.selectTeacherbyidandname3(1,"找钱");
session1.close();
}
测试结果
2019-04-07 21:37:33,282 [DEBUG] TeacherMapper - Cache Hit Ratio [TeacherMapper]: 0.0
2019-04-07 21:37:34,954 [DEBUG] TeacherMapper.selectTeacherbyidandname3 - ==> Preparing: select * from TEACHER WHERE id=? and name =?
2019-04-07 21:37:35,286 [DEBUG] TeacherMapper.selectTeacherbyidandname3 - ==> Parameters: 1(Integer), 找钱(String)
2019-04-07 21:37:35,357 [DEBUG] TeacherMapper.selectTeacherbyidandname3 - <== Total: 1
2019-04-07 21:37:35,468 [DEBUG] TeacherMapper - Cache Hit Ratio [TeacherMapper]: 0.5