很早之前就想学习mybatis,据说很多公司都使用这个框架。以前我都使用老掉牙的DBCP,Hibernate感觉太大,现在来学学这个中性的框架。
Java实战应用:Mybatis实现单表的增删改
Mybatis中对List<Object> 对象List的批处理插入操作
首先是环境的配置,我使用maven创建项目,pom.xml文件如下
<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 ">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bird</groupId>
<artifactId>concursey</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>concursey</name>
<url></url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
</dependencies>
</project>
还得创建一个数据库和对应的一张表做示范,这里就不写了,直接上对应的JavaBean
package com.bird.mybatis.bean;
public class Users {
private int id;
private String name;
private int age;
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 getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Users [id=" + id + ",, age=" + age + "]";
}
}
然后要给对应的JavaBean创建对应的mapper.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.bird.mybatis.bean.userMapper">
<!--根据ID获取对应的值 -->
<select parameterType="int" resultType="com.bird.mybatis.bean.Users">
select * from users where id = #{id}
</select>
</mapper>
当然还有mybatis的全局文件,conf.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>
<!-- development:开发模式 work:工作模式 -->
<environments default="development">
<environment>
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property value="com.mysql.jdbc.Driver" />
<property value="jdbc:mysql://localhost:3306/mybatis" />
<property value="root" />
<property value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/bird/mybatis/bean/userMapper.xml" />
</mappers>
</configuration>
最后是测试代码
package com.bird.mybatis.bean;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;