MyBatis开发及简介

来源:互联网 发布:云南2016年旅游数据 编辑:程序博客网 时间:2024/06/05 05:33

一、开发代码结构图


二、配置文件简介:

1、jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sampledb
jdbc.username=root
jdbc.password=root

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="jdbc.properties"/>
<!-- 
<typeAliases>
<typeAlias alias="Student" type="com.java.mybatis.model.Student"/>
</typeAliases>
-->
<typeAliases>
<package name="com.java.mybatis.model"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<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/java/mybatis/mappers/StudentMapper.xml" />
</mappers>
</configuration>

3、StudentMapper.xml:
<?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.java.mybatis.mappers.StudentMapper">
<insert id="add" parameterType="Student"  >
insert into t_student values(null,#{name},#{age})
</insert>
</mapper> 

4、StudentMapper.java:
package com.java.mybatis.mappers;


import com.java.mybatis.model.Student;


public interface StudentMapper {


public int add(Student student);
}

使用注解的代码如下:
import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.One;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import com.java.mybatis.model.Student;public interface StudentMapper {@Insert("insert into t_student values(null,#{name},#{age})")public int insertStudent(Student student);@Update("update t_student set name=#{name},age=#{age} where id=#{id}")public int updateStudent(Student student);@Delete("delete from t_student where id=#{id}")public int deleteStudent(int id);@Select("select * from t_student where id=#{id}")public Student getStudentById(Integer id);@Select("select * from t_student")@Results({@Result(id=true,column="id",property="id"),@Result(column="name",property="name"),@Result(column="age",property="age")})public List<Student> findStudents();@Select("select * from t_student where id=#{id}")@Results({@Result(id=true,column="id",property="id"),@Result(column="name",property="name"),@Result(column="age",property="age"),@Result(column="addressId",property="address",one=@One(select="com.java1234.mappers.AddressMapper.findById"))})public Student selectStudentWithAddress(int id);@Select("select * from t_student where gradeId=#{gradeId}")@Results({@Result(id=true,column="id",property="id"),@Result(column="name",property="name"),@Result(column="age",property="age"),@Result(column="addressId",property="address",one=@One(select="com.java1234.mappers.AddressMapper.findById"))})public Student selectStudentByGradeId(int gradeId);@Select("select * from t_student where id=#{id}")@Results({@Result(id=true,column="id",property="id"),@Result(column="name",property="name"),@Result(column="age",property="age"),@Result(column="addressId",property="address",one=@One(select="com.java1234.mappers.AddressMapper.findById")),@Result(column="gradeId",property="grade",one=@One(select="com.java1234.mappers.GradeMapper.findById"))})public Student selectStudentWithAddressAndGrade(int id);}


5、Student.java:

package com.java.mybatis.model;

 

public class Student {

private Integer id;

private String name;

private Integer age;

public Student() {

super();

}

public Student(String name, Integer age) {

super();

this.name = name;

this.age = age;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}



6、SqlSessionFactoryUtil.java:

package com.java.mybatis.util;

 

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 SqlSessionFactoryUtil {

private static SqlSessionFactory sqlSessionFactory;

public static SqlSessionFactory getSqlSessionFactory(){

if(sqlSessionFactory==null){

InputStream inputStream=null;

try{ inputStream=Resources.getResourceAsStream("mybatis-config.xml");

sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);

}catch(Exception e){

e.printStackTrace();

}

}

return sqlSessionFactory;

}

public static SqlSession openSession(){

return getSqlSessionFactory().openSession();

}

}


7、StudentTest.java:
package com.java.mybatis.service;


import org.apache.ibatis.session.SqlSession;


import com.java.mybatis.mappers.StudentMapper;
import com.java.mybatis.model.Student;
import com.java.mybatis.util.SqlSessionFactoryUtil;


public class StudentTest {


public static void main(String[] args) {
SqlSession sqlSession=SqlSessionFactoryUtil.openSession();
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
Student student=new Student("张三",12);
int result=studentMapper.add(student);
sqlSession.commit();
if(result>0){
System.out.println("添加成功!");
}
}
}

environments:

MyBatis 支持多个环境,可以任意配置;

transactionManager

MyBatis 支持两种类型的事务管理器:JDBC 和MANAGED(托管);

JDBC:应用程序负责管理数据库连接的生命周期;

MANAGED 由应用服务器负责管理数据库连接的生命周期; ( 一般商业服务器才   有此功能,JBOSS,WebLogic)

dataSource

用来配置数据源;类型有:UNPOOLED,POOLED,JNDI;

UNPOOLED,没有连接池,每次数据库操作,MyBatis 都会创建一个新的连接,用完 后,关闭;适合小并发项目;

POOLED,用上了连接池;

JNDI,使用应用服务器配置JNDI 数据源获取数据库连接;

 

 

properties

配置属性

typeAliases

给类的完成限定名取别名,方便使用;如下:


<!-- 
<typeAliases>
<typeAlias alias="Student" type="com.java.mybatis.model.Student"/>
</typeAliases>
-->
<typeAliases>
<package name="com.java.mybatis.model"/>
</typeAliases>

mappers

引入映射文件,例如mybatis-config.xml:

<mappers>
<!-- <mapper resource="com/java/mybatis/mappers/StudentMapper.xml" />   -->
<!--  <mapper class="com.java.mybatis.mappers.StudentMapper"/>-->
<package name="com.java.mybatis.mappers"/>
</mappers>

配置Log4j 日志

log4j.rootLogger=info,appender1,appender2
log4j.appender.appender1=org.apache.log4j.ConsoleAppender 


log4j.appender.appender2=org.apache.log4j.FileAppender 
log4j.appender.appender2.File=D:/logFile.txt


log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout 

三、一对多关系、多对一关系

四、动态 SQL

1、if 条件

<select id="searchStudents" parameterType="Map" resultMap="StudentResult">

select * from t_student

 where gradeId=#{gradeId}

 <if test="name!=null">

  and name like #{name}

 </if>

 <if test="age!=nulll">

  and age=#{age}

 </if>

</select>

2choosewhenotherwise条件

<resultMap type="Student" id="StudentResult">

<id property="id" column="id"/>

<result property="name" column="name"/>

<result property="age" column="age"/>

<association property="addressId" column="id" select="com.java.mybatis.mappers.AddressMapper.findById"></association>

</resultMap>

<select id="findStudentWithAddress" resultMap="StudentResult" parameterType="Integer">

select t1.id,t1.age,t1.name,t1.addressId from t_student t1,t_address t2 where t1.addressId=t2.id and t1.id=#{id}

</select>

3where条件

1,自动加上where;
2,如果where 子句以and 或者or 开头,则自动删除第一个and 或者or;
<select id="searchStudents3" parameterType="Map" resultMap="StudentResult">
select * from t_student
<where>
<if test="gradeId!=null">
gradeId=#{gradeId}
</if>
<if test="name!=null">
and name like #{name}
</if>
<if test="age!=nulll">
and age=#{age}
</if>
</where>
</select>

4、trim条件

功能和where 元素类似,提供了前缀,后缀功能,更加灵活;

<select id="searchStudents4" parameterType="Map" resultMap="StudentResult">
select * from t_student
<trim prefix="where" prefixOverrides="and|or">
<if test="gradeId!=null">
gradeId=#{gradeId}
</if>
<if test="name!=null">
and name like #{name}
</if>
<if test="age!=nulll">
and age=#{age}
</if>
</trim>
</select>

5、foreach 循环

<select id="searchStudents5" parameterType="Map" resultMap="StudentResult">

select * from t_student

 <if test="gradeIds!=null">

  <where>

  gradeId in

  <foreach item="gradeId" collection="gradeIds" open="(" separator="," close=")">

   #{gradeId}

  </foreach>

  </where>

 </if>

</select>

6、set条件

1,自动加上set;

2,自动剔除最后一个逗号“,”;

<update id="updateStudent" parameterType="Student">

update t_student

<set>

 <if test="name!=null">

  name=#{name},

 </if>

 <if test="age!=null">

  age=#{age},

 </if>

</set>

where id=#{id}

</update>

五、分页

1,逻辑分页;

@Test

public void testFindStudent(){

logger.info("查询学生");

int offset=0,limit=3;

RowBounds rowBounds=new RowBounds(offset,limit);

List<Student> studentList=studentMapper.findStudents(rowBounds);

for(Student student:studentList){

System.out.println(student);

}

}

2,物理分页;

<select id="findStudents2" parameterType="Map" resultMap="StudentResult">

select * from t_student

<if test="start!=null and size!=null">

limit #{start},#{size}

</if>

</select>


@Test

public void testFindStudent2(){

logger.info("查询学生");

Map<String,Object> map=new HashMap<String,Object>();

map.put("start", 3);

map.put("size", 3);

List<Student> studentList=studentMapper.findStudents2(map);

for(Student student:studentList){

System.out.println(student);

}

}

六、缓存

Mybatis 默认情况下,MyBatis 启用一级缓存,即同一个SqlSession 接口对象调用了相同的select 语句,则直

接会从缓存中返回结果,而不是再查询一次数据库;

开发者可以自己配置二级缓存,二级缓存是全局的;

默认情况下,select 使用缓存的,insert update delete 是不使用缓存的

<!--

     1size:表示缓存cache中能容纳的最大元素数。默认是1024

     2flushInterval:定义缓存刷新周期,以毫秒计;

      3eviction:定义缓存的移除机制;默认是LRU(least recently userd,最近最少使用),还有FIFO(first in first out,先进先出)

      4readOnly:默认值是false,假如是true的话,缓存只能读。

     -->

<cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"/>



原创粉丝点击