Ibatis3 入门学习笔记
一、 搭建环境
1. 下载包
下载地址: http://www.mybatis.org/java.html
2. 解压
3. 新建 web 项目 testMyBatis
并将解压出来的包拷贝到新建项目中的 WebRoot/lib 里 :
asm-1.5.3.jar
cglib-2.1_3.jar
commons-logging-1.1.1.jar
mybatis-3.0.1.jar
slf4j-api-1.5.8.jar
slf-log4j12-1.5.8.jar
由于我用到的是 SQL Server 数据库,所以要将相应的 DB 驱动拷贝到 lib 中:
Jtds-1.1.jar
4. 新建包
com.test.model
com.test.dao
二、 DB 表说明
要测试的表名 t_user, 结构如下:
CREATE TABLE [dbo] . [t_user] (
[id] [bigint] IDENTITY ( 1, 1) NOT NULL,
[name] [varchar] ( 20) NOT NULL,
[age] [int] NOT NULL
) ON [PRIMARY]
三、 创建对象文件
1.src/log4j.properties
log4j.rootLogger= DEBUG, stdout
log4j.appender.stdout= org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout= org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= %c {1} - %m%n
log4j.logger.java.sql.PreparedStatement= DEBUG
2.src/sqlmap-config.xml
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd" >
< configuration >
< typeAliases >
< typeAlias type = "com.test.model.User" alias = "user" />
</ typeAliases >
< environments default = "development" >
< environment id = "development" >
< transactionManager type = "JDBC" />
< dataSource type = "UNPOOLED" >
< property name = "driver"
value = "net.sourceforge.jtds.jdbc.Driver" />
< property name = "url" value = "jdbc:jtds:sqlserver://192.168.0.101:1433/test" />
< property name = "username" value = "test" />
< property name = "password" value = "123" />
</ dataSource >
</ environment >
</ environments >
< mappers >
< mapper resource = "com/test/model/User.xml" />
</ mappers >
</ configuration >
3.com.test.model.User.java
package com.test.model;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 8681358563101101660L;
private long id ;
private String name ;
private int age ;
public long getId() {
return id ;
}
public void setId( long 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;
}
}
4.com.test.model.User.xml
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd" >
< mapper namespace = "user" >
< resultMap type = "user" id = "userMapper" >
< result property = "id" column = "id" jdbcType = "BIGINT" />
< result property = "name" column = "name" jdbcType = "VARCHAR" />
< result property = "age" column = "age" jdbcType = "INTEGER" />
</ resultMap >
< select id = "getUserById" parameterType = "int" resultMap = "userMapper" >
select * from t_user where id = #{id}
</ select >
< select id = "getUserList" resultMap = "userMapper" >
select * from t_user
</ select >
< insert id = "insert" >
insert into t_user(name, age) values (#{name}, #{age})
</ insert >
< delete id = "delUserById" >
delete from t_user where id=#{id}
</ delete >
< update id = "update" >
update t_user set name = #{name}, age=#{age}
where id=#{id}
</ update >
</ mapper >
5.com.test.dao.IbatisSessionFactory.java
package com.test.dao;
import java.io.IOException;
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;
public class IbatisSessionFactory {
private static SqlSessionFactory sqlMapper;
private static SqlSession sqlSession;
static{
try{
String resource = "sqlmap-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlMapper = new SqlSessionFactoryBuilder().build(reader);
}catch(IOException e){
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
sqlSession = sqlMapper.openSession();
return sqlSession;
}
public static void closeSqlSession(){
if(sqlSession!=null){
sqlSession.close();
}
}
}
6.com.test.dao.UserDaoInte.java
package com.test.dao;
import java.util.List;
import com.test.model.User;
public interface UserDaoInte {
public User getUserById(Long id);
public void addUser(User user);
public void delUser(Long id);
public void updateUser(User user);
public List<User> getUserList();
}
7.com.test.dao.UserDao.java
package com.test.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.bd.dao.IbatisSessionFactory;
import com.test.model.User;
public class UserDao implements UserDaoInte{
@Override
public void addUser(User user) {
SqlSession session = IbatisSessionFactory.getSqlSession ();
session.insert( "insert" , user);
session.commit();
session.close();
}
@Override
public void delUser(Long id) {
SqlSession session = IbatisSessionFactory.getSqlSession ();
session.delete( "delUserById" , id);
session.commit();
session.close();
}
@Override
public User getUserById(Long id) {
SqlSession session = IbatisSessionFactory.getSqlSession ();
User user = (User)session.selectOne( "getUserById" , id);
session.commit();
session.close();
return user;
}
@Override
public void updateUser(User user) {
SqlSession session = IbatisSessionFactory.getSqlSession ();
session.update( "update" , user);
session.commit();
session.close();
}
@Override
public List<User> getUserList() {
SqlSession session = IbatisSessionFactory.getSqlSession ();
List<User> list = (List)session.selectList( "getUserList" );
session.commit();
session.close();
return list;
}
}
8. 写一个测试类 com.test.dao.Test.java
package com.test.dao;
import java.util.List;
import com.test.model.User;
public class Test {
public static void main(String[] args) {
UserDaoInte dao = new UserDao();
// 增加部分
User user = new User();
user.setAge(24);
user.setName( "name 4" );
dao.addUser(user);
// 获取单个对象部分
//User user = dao.getUserById(2L);
//System.out.println(user.getName());
// 更新部分
//user.setName("test name2");
//dao.updateUser(user);
// 删除
//dao.delUser(0L);
// 获取全部数据
//List<User> users = dao.getUserList();
//System.out.println(users.size());
}
}
四、 采用注解方式
1. com.test.model.User.xml
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd" >
< mapper namespace = "com.test.dao.UserDaoInte" ></ mapper >
2. UserDaoInte.java
package com.test.dao;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.test.model.User;
public interface UserDaoInte {
@Select ( "select * from t_user" )
public List<User> getUserList();
}
3. 测试代码
public static void main(String[] args) {
SqlSession session = IbatisSessionFactory.getSqlSession ();
UserDaoInte dao = session.getMapper(UserDaoInte. class );
List<User> list = dao.getUserList();
System. out .println(list.size());
}
4 .说明
在通过接口 + 元注释的方式定义 SqlMapper 。此时就不需要接口的实现类。