整体代码结构:
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>
<!-- 定义别名 -->
<typeAliases>
<typeAlias alias="role" type="com.learn.chapter2.po.Role" />
</typeAliases>
<!-- 定义数据库信息,默认使用development数据库构建环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="autoCommit" value="false"/>
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 定义映射器 -->
<mappers>
<mapper resource="com/learn/chapter2/mapper/RoleMapper.xml" />
</mappers>
</configuration>
RoleMapper.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.learn.chapter2.mapper.RoleMapper">
<!-- 查询 -->
<select id="getRole" parameterType="long" resultType="role">
select id,
role_name as roleName,
note
from t_role
where id = #{id}
</select>
<!-- 插入数据 -->
<insert id="insertRole" parameterType="role">
insert
into t_role(role_name,note)
values (#{roleName},#{note})
</insert>
<!-- 删除数据 -->
<delete id="deleteRole" parameterType="long">
delete from t_role where t.id = #{id}
</delete>
</mapper>
RoleMapper.java
package com.learn.chapter2.mapper;
import com.learn.chapter2.po.Role;
public interface RoleMapper {
public Role getRole(long id);
public void insertRole(Role role);
public void deleteRole(long id);
}
Role.java
package com.learn.chapter2.po;
public class Role {
private Long id;
private String roleName;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
SqlSessionFactoryUtil.java
package com.learn.chapter2.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
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 org.apache.log4j.Logger;
public class SqlSessionFactoryUtil {
//创建SqlSessionFactory实例
//单例模式
private static SqlSessionFactory sqlSessionFactory = null;
//私有化构造方法
private SqlSessionFactoryUtil(){};
//类线程锁
@SuppressWarnings("rawtypes")
private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class;
//创建实例
public static SqlSessionFactory initSqlSessionFactory(){
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try{
inputStream = Resources.getResourceAsStream(resource);
}catch (IOException e) {
Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log("", null, Level.SEVERE, e);
}
synchronized(CLASS_LOCK){
if(sqlSessionFactory==null){
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
return sqlSessionFactory;
}
}
//创建sqlsession
public static SqlSession openSqlSession(){
if(sqlSessionFactory==null){
initSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
Chapter2Main.java
package com.learn.chapter2.main;
import org.apache.ibatis.session.SqlSession;
import com.learn.chapter2.mapper.RoleMapper;
import com.learn.chapter2.po.Role;
import com.learn.chapter2.util.SqlSessionFactoryUtil;
public class Chapter2Main {
public static void main(String[] args) {
SqlSession sqlSession = null;
try{
sqlSession = SqlSessionFactoryUtil.openSqlSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role role = new Role();
role.setNote("a litte boy");
role.setRoleName("Tom");
roleMapper.insertRole(role);
sqlSession.commit();
Role res = roleMapper.getRole(3);
System.out.println("=================");
System.out.println("Res: " + res.getId() + "\n" +res.getRoleName() + "\n" + res.getNote());
System.out.println("=================");
}catch(Exception ex){
System.out.println("ex: " + ex.getMessage() + "\n");
sqlSession.rollback();
}finally{
sqlSession.close();
}
}
}
log4j.properties
#配置log4j的属性文件
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
MySQL DML & DDL:
create database mybatis;
show databases;
use mybatis;
create table t_role(
id int(20) primary key not null auto_increment,
role_name varchar(20),
note varchar(20)
);
show tables;
select * from t_role;
insert into t_role(role_name,note) value('HR','humen resources');
insert into t_role(role_name,note) value('IT','internet tech');
select * from t_role;
SQL:
Console:
DEBUG 2017-04-02 21:58:24,473 org.apache.ibatis.logging.LogFactory: Logging init
ialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG 2017-04-02 21:58:24,551 org.apache.ibatis.datasource.pooled.PooledDataSour
ce: PooledDataSource forcefully closed/removed all connections.
DEBUG 2017-04-02 21:58:24,554 org.apache.ibatis.datasource.pooled.PooledDataSour
ce: PooledDataSource forcefully closed/removed all connections.
DEBUG 2017-04-02 21:58:24,554 org.apache.ibatis.datasource.pooled.PooledDataSour
ce: PooledDataSource forcefully closed/removed all connections.
DEBUG 2017-04-02 21:58:24,554 org.apache.ibatis.datasource.pooled.PooledDataSour
ce: PooledDataSource forcefully closed/removed all connections.
DEBUG 2017-04-02 21:58:24,726 org.apache.ibatis.transaction.jdbc.JdbcTransaction
: Opening JDBC Connection
Sun Apr 02 21:58:24 CST 2017 WARN: Establishing SSL connection without server's
identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ an
d 5.7.6+ requirements SSL connection must be established by default if explicit
option isn't set. For compliance with existing applications not using SSL the ve
rifyServerCertificate property is set to 'false'. You need either to explicitly
disable SSL by setting useSSL=false, or set useSSL=true and provide truststore f
or server certificate verification.
DEBUG 2017-04-02 21:58:25,074 org.apache.ibatis.datasource.pooled.PooledDataSour
ce: Created connection 507084503.
DEBUG 2017-04-02 21:58:25,075 org.apache.ibatis.transaction.jdbc.JdbcTransaction
: Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection
@1e397ed7]
DEBUG 2017-04-02 21:58:25,076 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>
Preparing: insert into t_role(role_name,note) values (?,?)
DEBUG 2017-04-02 21:58:25,128 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>
Parameters: Tom(String), a litte boy(String)
DEBUG 2017-04-02 21:58:25,131 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==
Updates: 1
DEBUG 2017-04-02 21:58:25,133 org.apache.ibatis.transaction.jdbc.JdbcTransaction
: Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1e397ed7]
DEBUG 2017-04-02 21:58:25,139 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>
Preparing: select id, role_name as roleName, note from t_role where id = ?
DEBUG 2017-04-02 21:58:25,140 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>
Parameters: 3(Long)
DEBUG 2017-04-02 21:58:25,168 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==
Total: 1
=================
Res: 3
Lucy
just mark
=================
DEBUG 2017-04-02 21:58:25,169 org.apache.ibatis.transaction.jdbc.JdbcTransaction
: Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connectio
n@1e397ed7]
DEBUG 2017-04-02 21:58:25,174 org.apache.ibatis.transaction.jdbc.JdbcTransaction
: Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1e397ed7]
DEBUG 2017-04-02 21:58:25,174 org.apache.ibatis.datasource.pooled.PooledDataSour
ce: Returned connection 507084503 to pool.