MyBatis获取SqlSession
首先获取SqlSessionFactory:
Reader reader=Resources.getResourceAsReader(“Configuration.xml”);
SqlSessionFactory sf=new SqlSessionFactoryBuilder().build(reader);
获取SqlSession:
sf.openSession();
deptDTO:属性 deptno、dname、loc;
DeptMapper:增删改查方法
定义命名空间 :
定义结果集:
id="RM.Dept" type="com.test.dto.DeptDTO">
<result property="deptno" column="deptno"/>
<result property="dname" column="dname"/>
<result property="loc" column="loc"/>
插入insert:
–插入需要一个参数DTO,参数类型为:com.test.dto.DeptDTO
<insert id="Dept.insert" parameterType="com.test.dto.DeptDTO">
insert>
DAO-INSERT:
public void insert(Object obj){
SqlSession session=SqlSessionFactoryUtil.getSqlSession();
session.insert(namespace+"insert",obj);
session.commit();
}
删除delete:
–删除时根据id删除 参数类型为int
<delete id="Dept.delete" parameterType="int">
delete>
public void delete(int id){
SqlSession session=SqlSessionFactoryUtil.getSqlSession();
session.delete(namespace+"delete", id);
session.commit();
}
<update id="Dept.update" >
update>
public void update(Object obj){
SqlSession session=SqlSessionFactoryUtil.getSqlSession();
session.update(namespace+"update",obj);
session.commit();
}
<select id="Dept.getById" resultMap="RM.Dept">
SELECT <include refid="Dept.columns" />
select>
public Object query(int id){
SqlSession session=SqlSessionFactoryUtil.getSqlSession();
Object obj=session.selectOne(namespace+"getById", id);
return obj;
}
Configuration.xml文件:
根据数据库不同,配置不同的参数。
<configuration>
<environments default="myexample">
<environment id="myexample">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/emp" />
<property name="username" value="root" />
<property name="password" value="123456" />
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/test/mapper/DeptMapper.xml"/>
mappers>
configuration>
SqlSessionFactoryUtil:
public class SqlSessionFactoryUtil {
// 定义一个私有的构造方法 单例模式
private SqlSessionFactoryUtil(){}
private static SqlSessionFactory sf;
// 静态块 初始化Configuration.xml
static
{
try {
Reader reader=Resources.getResourceAsReader("Configuration.xml");
sf=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
// 如果静态语句块初始化失败,尝试再初始化一次
public static SqlSessionFactory getSqlSessionFactory(){
if(sf==null){
sf=initSqlSessionFactory();
}
return sf;
}
public static SqlSessionFactory initSqlSessionFactory(){
try {
Reader reader=Resources.getResourceAsReader("Configuration.xml");
sf=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
return sf;
}
public static SqlSession getSqlSession(){
return sf.openSession();
}
}
我的心愿是:
好好学习
天天向上
世界和平
!