mybatis
环境
jdk 1.7
集成工具Idea
管理工具maven-3.0.4
新建一个maven工程
修改maven配置
在file的settings中
修改maven的setting.xml
设置自己的本地maven库
<localRepository>G:\MavenWareHouse</localRepository>
云端用阿里仓库
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
添加依赖
在pom.xml中添加junit、mysql-connector-java、mybatis、log4j等四个依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
添加配置文件
添加log4j.properties日志配置
### set log levels ###
log4j.rootLogger = DEBUG,Console
### console ###
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= %d{ABSOLUTE} %5p %c{1}:%L - %m%n
#### file ##
添加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>
<environments default="development">
<environment id="development">
<!-- 事务管理器 -->
<transactionManager type="JDBC" />
<!-- 数据源的配置 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/ssm" />
<property name="username" value="root" />
<property name="password" value="852258" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/google/first/mapper/EmpMapper.xml" />
</mappers>
</configuration>
URI未注册解决
在settings如下注册
在浏览器中打开链接会下载一个文件http://mybatis.org/dtd/mybatis-3-mapper.dtd
如下添加文件
创建mapper、dao、model三个包
maven的文件位置
1.maven项目下,sources下的java文件,resources下的资源文件才会被编译。
2.maven项目下,会将resources类型的文件夹作为 资源文件的根目录,编译之后,资源文件是直接在classes下的
model为数据模型包
对应数据库中的数据
package rui.zhang.model;
//序列化 目的 让别的计算机可以读取我的对象
public class Emp implements java.io.Serializable {
private static final long serialVersionUID = -1428944907928344834L;
private int id;
private String name;
private int salary;
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 getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
mapper为映射包
将java的操作映射为对数据库的操作
<?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="rui.zhang.mapper.EmpMapper">
<insert id="addEmp" parameterType="rui.zhang.model.Emp" useGeneratedKeys="true" keyProperty="id">
INSERT INTO emp (name, age, salary) VALUES (#{name}, #{age}, #{salary})
</insert>
</mapper>
先来测试一下
看数据是否提交成功
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 rui.zhang.model.Emp;
import java.io.IOException;
import java.io.InputStream;
public class EmpTest {
public static void main(String[] args) {
String resource= "mybatis-config.xml";
InputStream is=null;
SqlSessionFactory sessionFactory=null;
SqlSession session=null;
try {
is= Resources.getResourceAsStream(resource);
sessionFactory=new SqlSessionFactoryBuilder().build(is);
System.out.println(sessionFactory);
session=sessionFactory.openSession();
Emp emp=new Emp("张瑞",15000,21);
session.insert("rui.zhang.mapper.EmpMapper.addEmp",emp);
int i=emp.getId();
System.out.println(i);
session.commit();
} catch (IOException e) {
session.rollback();
e.printStackTrace();
}finally {
try {
if (session!=null)
session.close();
if (is!=null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
编写创建返回SqlSessionFactory的方法
package rui.zhang.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.InputStream;
public class DBUtils {
private static String resource="mybatis-config.xml";
private static InputStream inputStream=null;
private static SqlSessionFactory sqlSessionFactory=null;
static {
try {
inputStream= Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory!=null){
return sqlSessionFactory;
}else{
try {
inputStream= Resources.getResourceAsStream(resource);
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
return sqlSessionFactory;
}
}
增添数据
编写mapper
<insert id="addEmp" parameterType="rui.zhang.model.Emp" useGeneratedKeys="true" keyProperty="id">
insert into emp(name,salary,age) values(#{name},#{salary},#{age})
</insert>
编写dao
public int addEmp(Emp emp){
int id=0;
SqlSession session=null;
try {
session=DBUtils.getSqlSessionFactory().openSession();
session.insert("rui.zhang.mapper.EmpMapper.addEmp",emp);
id=emp.getId();
session.commit();
} catch (Exception e) {
logger.error(e);
session.rollback();
throw new RuntimeException();
} finally {
if (session!=null){
session.close();
}
}
return id;
}
测试
@Test
public void testAddEmp(){
Emp emp=new Emp("高李燕",50000,22);
try {
int i=empDao.addEmp(emp);
} catch (Exception e) {
e.printStackTrace();
}
}
删、改、查与增步骤类似
mapper
<?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="rui.zhang.mapper.EmpMapper">
<insert id="addEmp" parameterType="rui.zhang.model.Emp" useGeneratedKeys="true" keyProperty="id">
insert into emp(name,salary,age) values(#{name},#{salary},#{age})
</insert>
<!--java内置类型不需要传入 只需要传入自定义内容-->
<delete id="delEmp">
DELETE FROM emp WHERE id=#{eid}
</delete>
<update id="upEmp" parameterType="rui.zhang.model.Emp">
UPDATE emp SET NAME = #{name},salary = #{salary},age =#{age} WHERE id=#{id}
</update>
<select id="queryEmp" resultType="rui.zhang.model.Emp">
SELECT name,salary,age FROM emp
</select>
</mapper>
dao
package rui.zhang.dao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import rui.zhang.model.Emp;
import rui.zhang.util.DBUtils;
import java.util.List;
public class EmpDao {
//日志记录
private Logger logger= Logger.getLogger(EmpDao.class);
public int addEmp(Emp emp){
int id=0;
SqlSession session=null;
try {
session=DBUtils.getSqlSessionFactory().openSession();
session.insert("rui.zhang.mapper.EmpMapper.addEmp",emp);
id=emp.getId();
session.commit();
} catch (Exception e) {
logger.error(e);
session.rollback();
throw new RuntimeException();
} finally {
if (session!=null){
session.close();
}
}
return id;
}
public int delEmp(int id){
int i=0;
SqlSession session=null;
try {
session=DBUtils.getSqlSessionFactory().openSession();
i=session.delete("rui.zhang.mapper.EmpMapper.delEmp",id);
session.commit();
} catch (Exception e) {
logger.error(e);
session.rollback();
throw new RuntimeException();
} finally {
if (session!=null){
session.close();
}
}
return i;
}
public int upEmp(Emp emp){
int i=0;
SqlSession session=null;
try {
session=DBUtils.getSqlSessionFactory().openSession();
i=session.update("rui.zhang.mapper.EmpMapper.upEmp",emp);
session.commit();
} catch (Exception e) {
logger.error(e);
session.rollback();
throw new RuntimeException();
} finally {
if (session!=null){
session.close();
}
}
return i;
}
public List<Emp> queryEmp(){
List<Emp> list=null;
SqlSession sqlSession=null;
try {
sqlSession=DBUtils.getSqlSessionFactory().openSession();
list=sqlSession.selectList("rui.zhang.mapper.EmpMapper.queryEmp");
} catch (Exception e) {
logger.error(e);
throw new RuntimeException();
}finally {
if (sqlSession!=null){
sqlSession.close();
}
}
return list;
}
}
测试
import org.junit.Test;
import rui.zhang.dao.EmpDao;
import rui.zhang.model.Emp;
import java.util.List;
public class EmpTestDao {
private static EmpDao empDao=new EmpDao();
@Test
public void testAddEmp(){
Emp emp=new Emp("高李燕",50000,22);
try {
int i=empDao.addEmp(emp);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testDelEmp(){
try {
int i=empDao.delEmp(18);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testUpdateEmp(){
Emp emp=new Emp("张冯",50000,25);
emp.setId(17);
try {
int i=empDao.upEmp(emp);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testQueryEmp(){
try {
List<Emp> list=empDao.queryEmp();
for (Emp emp:list
) {
System.out.println(emp.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}