2014/12/8
最近公司的项目是springmvc+spring+mybatis+orcale的一个项目,正好这节以该项目作为学习内容:
MyBatis消除了JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和POJO映射成数据库中的记录。
1.搭建开发环境:
eclipse-jee-luna,mysql 5.1 ,jdk 1.7,mybatis3.2.3.jar,log4j-1.2.12.jar,mysql-connector-java-5.1.22-bin.jar
新建web项目
在casserver数据库中新建一个user表:
在src目录下新建mybatis_jdbc.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="User" type="org.nick.model.User"/>
</typeAliases>
<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/casserver" />
<property name="username" value="root"/>
<property name="password" value="111122"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/nick/model/User.xml"/>
</mappers>
</configuration>
typeAlias:设置别名,一般要设置与model关联;创建model,添加get/set方法:
package org.nick.model;
public class User {
private int id;
private String userName;
private String userAge;
private String userAddress;
}
创建映射文件:
<?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="org.nick.mapper.IUserDao">
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
对m
apper namespace说明一下:指向一个对model操作的接口,所以在命名时以ImodelDao 形式命名,便于区分;
***接口下的方法名与mapper中的id名一致;创建IUserDao:
package org.nick.mapper;
import org.nick.model.User;
public interface IUserDao {
public User selectUserByID(int x);
}
测试:
package org.nick.test;
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;
import org.nick.mapper.IUserDao;
public class Test {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static{
try{
reader = Resources.getResourceAsReader("mybatis_jdbc.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}catch(Exception e){
e.printStackTrace();
}
}
public static SqlSessionFactory getSession(){
return sqlSessionFactory;
}
public static void main(String[] args) {
SqlSession session = getSession().openSession();
IUserDao userdao=session.getMapper(IUserDao.class);
System.out.println( userdao.selectUserByID(1).getUserName());
}
}
print:skx
每次启动session时候都要读取mybatis_jdbc.xml文件,和实例化reader、session,采用spring的通知解决这些问题,下节将以公司项目采用springmvc+spring+mybatis全程分析;