目录
引言
mybatis目前是业内主流操作数据库的框架,相比JDBC而言,不需要啥都写。首先创建一个maven工程,输入相应的groupId和ArtifactId,记住这两个值留待后用。首先看看整个工程的目录结构,之后逐一介绍:
本项目以MySQL为数据库,创建好工程后在pom.xml 中加入mybatis和mysql依赖库
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com</groupId>
<artifactId>sogou</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</project>
配置文件
在resource目录下创建三个文件db.properties( 配置数据库信息)\mybatis.xml(配置数据库加载信息)\sql.xml(撰写sql语句)。注意事项全部在代码中有注释,不在赘述。
db.properties( 配置数据库信息)
mysql.driver = com.mysql.jdbc.Driver
mysql.url = jdbc:mysql://*.*.*.*:3306/mydb?characterEncoding=utf-8
mysql.username = ***
mysql.password = ***
mybatis.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="db.properties"/>
<!-- 可设置多个连接环境信息 -->
<environments default="mysql_developer">
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库链接信息 -->
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--映射sql操作的文件 -->
<mapper resource="sql.xml"/>
</mappers>
</configuration>
sql.xml(撰写sql语句)
里面写sql语句,如下创建一个查询返回的实体映射studentMap和Insert插入操作以及findByCondition条件查询
<?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">
<!-- namespace命名空间,必须与创建maven groupId + artifactId组成
否则,在配置文件mybatis.xml中无法找到映射文件
-->
<mapper namespace="com.xzy">
<!-- resultMap标签:映射实体类与数据库表
type属性:表示实体类名
id属性:为实体类与数据库表映射的唯一名字
-->
<resultMap type="studentBean" id="studentMap">
<!-- id标签:映射主键属性;result标签:映射非主键属性
property属性:实体bean类属性名
column属性:数据库表的字段名
顺序无关,字段需对应
-->
<id property="studentID" column="studentID"/>
<result property="age" column="age"/>
<result property="name" column="name"/>
</resultMap>
<insert id="Insert" parameterType="studentBean">
INSERT INTO student (name, age, studentID) VALUES (#{name},#{age},#{studentID});
</insert>
<!--条件查询,注意部分字符需转义,如小于,<![CDATA[ < ]]>
resultMap为上诉建立的实体对象
-->
<select id="findByCondition" parameterType="int" resultMap="studentMap">
select * from student where age <![CDATA[ < ]]>#{age};
</select>
</mapper>
撰写代码
studentBean实体类
该实体类与数据库中表对应,构造函数需参数顺序需与数据库中表字段先后顺序相对应。本人并未发现mybatis能创表,所以事先得将表创建,本例数据表为student表(studentID[主键],name,age),如图
public class studentBean {
private String name;
private String studentID;
private int age;
/**
* 构造函数参数的顺序必须和数据库字段的顺序一致,否则在执行查询时
* 返回的对象无法转成该对象,从而报类似No constructor found in studentBean matching [java.lang.String, java.lang.String, java.lang.Integer]
* 异常
* **/
public studentBean(String name, String studentID, int age) {
this.name = name;
this.age = age;
this.studentID = studentID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
@Override
public String toString() {
return "studentBean{" +
"name='" + name + '\'' +
", studentID='" + studentID + '\'' +
", age=" + age +
'}';
}
}
MybatisUtil操作类
用于操作mysql数据库,插入和条件查询的调用需sql.xml里面命名空间加ID组成
import java.io.IOException;
import java.io.Reader;
import java.util.List;
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 MybatisUtil {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
private static SqlSessionFactory sqlSessionFactory;
/**
* 加载位于src/mybatis.xml配置文件
*/
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 禁止外界通过new方法创建
*/
private MybatisUtil(){}
/**
* 获取SqlSession
*/
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象为空
if(sqlSession == null){
//在SqlSessionFactory非空的情况下,获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();
//将SqlSession对象与当前线程绑定在一起
threadLocal.set(sqlSession);
}
//返回SqlSession对象
return sqlSession;
}
/**
* 关闭SqlSession与当前线程分开
*/
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
threadLocal.remove();
}
}
public static void insert(studentBean student){
//得到连接对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
try{
//映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL
sqlSession.insert("com.xzy.Insert", student);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally{
MybatisUtil.closeSqlSession();
}
}
public static List<studentBean> selectByConf(int conf){
SqlSession sqlSession = MybatisUtil.getSqlSession();
List list = null;
try{
list = sqlSession.selectList("com.xzy.findByCondition", conf);
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally{
MybatisUtil.closeSqlSession();
}
return list;
}
}
main入口
进行了链接测试,插入测试和条件查询测试
import java.sql.Connection;
import java.util.List;
public class testMain {
public static void main(String[] args) {
Connection conn = MybatisUtil.getSqlSession().getConnection();
System.out.println(conn!=null?"连接成功":"连接失败");
studentBean bean = new studentBean("小李子", "20180809005", 21);
MybatisUtil.insert(bean);
List<studentBean> studentList = MybatisUtil.selectByConf(23);
if (studentList != null){
for (studentBean student : studentList){
System.out.println(student.toString());
}
}
}
}
终端输出显示为:
连接成功
studentBean{name='小红', studentID='20180809001', age=21}
studentBean{name='小芳', studentID='20180809002', age=20}
studentBean{name='小李子', studentID='20180809005', age=21}
参考文献
https://segmentfault.com/a/1190000013661958#articleHeader13
https://blog.csdn.net/lucia_fanchen/article/details/49386327
http://www.mybatis.org/mybatis-3/zh/getting-started.html