导入三个包
Mysql mysql-connector-java-5.1.39-bin.jar
Mybatis mybatis-3.4.6.jar
打印日志 log4j-1.2.17.jar
Mybatis可用xml配置文件
首先创建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文件,里面存放driver,url,username,password的数据库信息 -->
<properties resource="mysql.properties"/>
<!-- 为类设置别名,否则在mapper配置中要输入完整包名 -->
<typeAliases>
<typeAlias alias="customer" type="com.shpun.entity.Customer"/>
</typeAliases>
<!-- 配置数据库信息 -->
<environments default="testCustoemr">
<environment id="testCustomer">
<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>
</configuration>
通过mybatis-config.xml构建SqlSessionFactory
package com.shpun.utils;
public class SqlSessionFactoryUtils {
private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
private static SqlSessionFactory sqlSessionFactory;
private SqlSessionFactoryUtils(){}
public static SqlSessionFactory getSqlSessionFactory(){
synchronized (LOCK){
if(sqlSessionFactory != null){
return sqlSessionFactory;
}
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
// 读取 mybatis-config.xml 配置文件
inputStream = Resources.getResourceAsStream(resource);
// 根据配置文件构建 SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (Exception e){
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
// 提供获取 SqlSession 的方法
public static SqlSession openSqlSession(){
if(sqlSessionFactory == null){
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
创建JavaBean Customer
package com.shpun.entity;
public class Customer {
private String id;
private String name;
private String gender;
private String birthday;
private String tel;
private String email;
private String introduction;
/*getter setter*/
}
定义映射器 需要Java接口和xml文件
创建CustomerMapper接口
package com.shpun.mapper;
public interface CustomerMapper {
int insertCustomer(Customer customer);
int deleteCustomer(String id);
int updateCustomer(Customer customer);
Customer selectCustomer(String id);
List<Customer> selectAllCustomer();
}
创建CustomerMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 使Mybatis能找到该接口 -->
<mapper namespace="com.shpun.mapper.CustomerMapper">
<!-- 默认自动映射,即表column与JavaBean的变量名要一致,可通过加as实现 -->
<!-- parameterType="customer" 传入的参数为customer,customer在mysql-config.xml中已经定义了别名
若未定义,应完整包名com.shpun.entity.Customer
-->
<!-- useGeneratedKeys="true" 使用Statement的getGeneratedKeys()进行主键回填,获取新插入的主键
keyProperty="id" 为填入 JavaBean 中的哪个属性 Customer 中为 id
-->
<insert id="insertCustomer" parameterType="customer" useGeneratedKeys="true" keyProperty="id">
insert into customers (name,gender,birthday,tel,email,introduction) value (#{name},#{gender},#{birthday},#{tel},#{email},#{introduction})
</insert>
<!-- parameterType="string" 为系统定义别名 Java类型为 String -->
<delete id="deleteCustomer" parameterType="string">
delete from customers where id=#{id}
</delete>
<update id="updateCustomer" parameterType="customer">
update customers set name=#{name},gender=#{gender},birthday=#{birthday},tel=#{tel},email=#{email},introduction=#{introduction} where id=#{id}
</update>
<select id="selectCustomer" parameterType="string" resultType="customer">
select * from customers where id=#{id}
</select>
<select id="selectAllCustomer" resultType="customer">
select * from customers
</select>
<!-- 定义结果集映射规则等 用于Select
默认是自动映射,即表column与JavaBean属性名要一致,也可在select中用as修改,
使用默认,则select中为resultType="customer"
若要使用下列resuleMap,替换select中resultType="customer"为resultMap="customerMap"
<resultMap id="customerMap" type="customer">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="gender" column="gender"></result>
<result property="birthday" column="birthday"></result>
<result property="tel" column="tel"></result>
<result property="email" column="email"></result>
<result property="introduction" column="introduction"></result>
</resultMap>
-->
</mapper>
创建完映射一定一定一定要到mybatis-config.xml中添加
<!-- 配置完映射xml,需要在mybatis-config.xml中添加 -->
<mappers>
<mapper resource="com/shpun/mapper/CustomerMapper.xml"/>
<!--
或包名引入 则自动扫描
<package name="com/shpun/mapper"/>
-->
</mappers>
mybatis-config.xml->工具类->JavaBean->Mapper的接口和xml文件
测试使用
Logger log = Logger.getLogger(TestMybatis.class);
SqlSession sqlSession = null;
try{
// 获取SqlSeesion
sqlSession = SqlSessionFactoryUtils.openSqlSession();
// 获取Mapper
CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
log.info(customerMapper.selectAllCustomer());
/* 增删改需要添加
sqlSession.commit();
*/
}catch (Exception e){
e.printStackTrace();
/* 增删改需要添加
sqlSession.rollback();
*/
}finally {
// 使用完要关闭
if(sqlSession != null){
sqlSession.close();
}
}
使用log4j需要添加log4j.properties
log4j.rootLogger=DEBUG,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %c: %m%n
网友评论