日期:2017/12/6
一、回顾 java 的 interface 语法:特殊的抽象类 + 方法必须无实体。(参考 Java(4):基础:面向对象学习的重要点 )
二、回顾sql在User.xml的封装(namespace + id):((5)MyBatis小总结:一个简单的例子)
<?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="User"> <select id="selectUser" resultType="mybatis.User"> select * from employee where id=#{id}
三、Mybatis的接口编程,恰好是使用 interface_name + method_name 组成唯一的 sql 设定。3.1 UserImp.java
package mybatis; //运用OOP编程思想,给xml做过改进 --- 接口编程 public interface UserImp { //定义方法,interface 只能定义方法,无法实现方法体。 public User getUserById(Integer id); }
3.2 改进后的 User.xml
<?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="mybatis.UserImp"> <select id="getUserById" resultType="mybatis.User"> select * from employee where id=#{id} </select> </mapper>
3.3 configuration.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> <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://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mybatis/User.xml" /> </mappers> </configuration>
3.4 testcase2.java
package mybatis; 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 testcase2 { public static void main(String [] args) throws IOException{ String resource = "mybatis/configuration.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sessionFactory.openSession(); try{ //获得 接口对象 UserImp usermapper = session.getMapper(UserImp.class); User user = usermapper.getUserById(1); System.out.println(user); }finally{ session.close(); } } }
测试结果:
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory). log4j:WARN Please initialize the log4j system properly.
Employee [id=1, lastName=mmb, email=144@qq.com, gender=0]
效果与此前一样。