标签:
MyBatis简介
MyBatis是支持普通SQL查询、存储过程和高级映射的优秀持久层框架,MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO映射成数据库中的记录。
MyBatis框架结构
MyBatis工作原理
注解方式配置第一个Mybatis实例
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/DB_Student
jdbc.username=root
jdbc.password=*****
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>
<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="true"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings>
<!-- Continue going here -->
<properties resource="db.properties"></properties>
<typeAliases>
<typeAlias type="po.Student" alias="Student"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<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="po/StudentMapper.xml"/>
</mappers>
</configuration>
StudentMapper接口
package mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import po.Student;
/**
* Created with IntelliJ IDEA.
* User: YEN
* Date: 2016/8/8
* Time: 08:24
*/
public interface StudentMapper {
@Insert("insert into tb_student(id,name,score) values (#{id},#{name},#{socre})")
public void insertStudent(Student student) throws Exception;
@Select("select * from tb_student where id=#{id}")
public void selectStudent(int id) throws Exception;
}
student.java
package po;
/**
* Created with IntelliJ IDEA.
* User: YEN
* Date: 2016/8/8
* Time: 08:20
*/
/**
* 类中的属性字段和数据库中的Student字段一一对应
*/
public class Student {
private int id;
private String name;
private int score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
/**
* 必须要有无参构造函数
*/
public Student(){
}
public Student(int id,String name,int socre){
this.id=id;
this.name=name;
this.score=socre;
}
@Override
public String toString(){
String str="学号:"+id+" 姓名:"+name+" 分数:"+score;
return str;
}
}
MyBatisUtil.java
package util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
/**
* Created with IntelliJ IDEA.
* User: YEN
* Date: 2016/8/8
* Time: 08:49
*/
/**
* 单例模式返回SqlSessionFactory
*/
public class MyBatisUtil {
private final static SqlSessionFactory SQL_SESSION_FACTORY;
static {
String resource="config/mybatis.xml";
Reader reader=null;
try {
reader= Resources.getResourceAsReader(resource);
} catch ( IOException e ) {
e.printStackTrace();
}
SQL_SESSION_FACTORY=new SqlSessionFactoryBuilder().build(reader);
}
public static SqlSessionFactory getSqlSessionFactory(){
return SQL_SESSION_FACTORY;
}
}
测试类MyBatisTest.java
package test;
import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import po.Student;
import util.MyBatisUtil;
/**
* Created with IntelliJ IDEA.
* User: YEN
* Date: 2016/8/8
* Time: 08:53
*/
public class MyBatisTest {
static SqlSessionFactory sqlSessionFactory= MyBatisUtil.getSqlSessionFactory();
public static void main(String[] args) {
addStudent(new Student(1,"YEN",100));
}
public static void addStudent(Student student){
SqlSession sqlSession=sqlSessionFactory.openSession();
try {
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
studentMapper.insertStudent(student);
sqlSession.commit();
} catch ( Exception e ) {
e.printStackTrace();
}
finally {
sqlSession.close();
}
}
}
XML文件配置方式实现
吧StudentMapper.java中的注解去掉,加上
StudentMapper.xml和Student在同一目录
<?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="po.Student">
<!--id要与StudentMapper中接口名称相同-->
<insert id="insertStudent" parameterMap="po.Student">
INSERT INTO tb_student(id,name,score) values (#{id},#{name},#{socre})
</insert>
<select id="selectStudent" resultType="Student" parameterType="int">
SELECT * FROM tb_student WHERE id=#{id}
</select>
</mapper>
开发技巧
<insert id="insertStudent" parameterMap="po.Student">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
-- 如果主键是自动增长的,需要获取刚刚插入的主键
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO..........
</insert>
* #{}和${}*
#{}表示一个占位符号,#{}接收输入参数,类型可以是简单类型,pojo、hashmap。
如果接收简单类型,#{}中可以写成value或其它名称。
#{}接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。
${}表示一个拼接符号,会引用sql注入,所以不建议使用${}。
${}接收输入参数,类型可以是简单类型,pojo、hashmap。
如果接收简单类型,${}中只能写成value。
${}接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。
标签:
原文地址:http://blog.csdn.net/yen_csdn/article/details/52148294