MyBatis配置文件
mybatis-config.xml <properties resource>元素可以指定properties文件位置,导入里面配置的值 <typeAlias>定义了一些别名,如student,用来代替全名com..Student <mapper>元素配置mapper.xml的位置
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3<configuration> 4 <properties resource="com/endless/mybatis/helloworld/config/jdbc.properties" /> 5 <typeAliases> 6 <typeAlias alias="student" type="com.endless.mybatis.helloworld.po.Student"></typeAlias> 7 </typeAliases> 8 <environments default="development"> 9 <environment id="development"> 10 <transactionManager type="JDBC" /> 11 <dataSource type="POOLED"> 12 <property name="driver" value="${driver}"/> 13 <property name="url" value="${url}"/> 14 <property name="username" value="${username}"/> 15 <property name="password" value="${password}"/> 16 </dataSource> 17 </environment> 18 </environments> 19 <mappers> 20 <mapper resource="com/endless/mybatis/helloworld/config/student-mapper.xml" /> 21 </mappers> 22</configuration>
jdbc.properties
1driver=com.mysql.jdbc.Driver 2url=jdbc:mysql://localhost:3306/school 3username=root 4password=1234
mapper配置文件
student-mapper.xml 这个文件里面配置sql,namespace为对于DAO接口 <select>定义了一条select语句,id对应上面namespace定义接口里的方法,parameterType和resultType分别对应该方法的参数和返回类型
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 4<mapper namespace="com.endless.mybatis.helloworld.mapper.StudentMapper"> 5 <!-- student是在mybatis-config.xml中配置的Alias --> 6 <select id="getStudent" parameterType="String" resultType="student"> 7 select * from student where id=#{studentId} 8 </select> 9</mapper>
Mapper接口
1public interface StudentMapper { 2 public Student getStudent(String studentId); 3} 4//这里Student的属性名称对和数据库的字段一致,会自动填充到Student对象中返回 5public class Student { 6 private int id; 7 private String name; 8 private int age; 9 private String gender; 10 //省略get,set 11}
测试程序
1public class MyBatisTest { 2 public static void main(String[] args){ 3 String resource="com/endless/mybatis/helloworld/config/mybatis-config.xml"; 4 SqlSession sqlSession=null; 5 try{ 6 //SqlSessionFactoryBuilder读取配置文件创建SqlSessionFactory对象 7 SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource)); 8 //sqlSessionFactory对象用来创建session,相当于JDBC的Connection对象 9 sqlSession=sessionFactory.openSession(); 10 StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class); 11 Student student=studentMapper.getStudent("10001"); 12 System.out.println(student); 13 }catch(Exception e){ 14 e.printStackTrace(); 15 }finally{ 16 if(sqlSession!=null) 17 sqlSession.close(); 18 } 19 } 20}
总结
