主配置文件,放入src下
<?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> <environments default="mysql"> <!-- MySQL --> <environment id="mysql"> <!-- JDBC提交和回滚机制 --> <transactionManager type="JDBC"/> <!-- JDBC连接对象的数据源连接池的实现 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/> <property name="username" value="root"/> <property name="password" value="1234"/> </dataSource> </environment> <!-- Oracle --> </environments> <!-- 关联映射文件 --> <mappers> <mapper resource="com/xms/entity/mapper/EmpMapper.xml"/> <mapper resource="com/xms/entity/mapper/DeptMapper.xml"/> </mappers> </configuration>
mapper放在com.xms.entity.mapper下,它的命名空间和id是跟EmpMapper.java接口一一对应的
EmpMapper.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.xms.dao.EmpMapper"> <select id="findAll" resultType="com.xms.entity.Emp"> select * from emp </select> </mapper>
EmpMapper.java 放在com.xms.dao下
package com.xms.dao; import java.util.List; import com.xms.entity.Emp; public interface EmpMapper { List<Emp> findAll(); Emp findByEmpno(int empno); void save(Emp emp); void update(Emp emp); void delete(Emp emp); }
MyBatisUtil.java 放在com.xms.util下,加载配置文件,获得SqlSession
package com.xms.util; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { private static SqlSessionFactory ssf; static{ //加载配置文件 SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder(); ssf = ssfb.build(MyBatisUtil.class .getClassLoader().getResourceAsStream("iBatis.xml")); } //获取SqlSession public static SqlSession getSession(){ return ssf.openSession(); } public static void main(String[] args) { System.out.println(MyBatisUtil.getSession()); } }
参考文件SpringMyBatisDay06_02