Mybatis入门
pom.xml
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.1</version>
</dependency>
</dependencies>
SqlMapConfig.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标签用于起别名,这样package指定包中的实体类的类名可以在Mapper.xml的resultType中直接使用,无需写全限定类名-->
<typeAliases>
<package name="com.company.domain"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///eesy"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--<mapper resource="com/aiitec/dao/IAccountMapper.xml"></mapper>-->
<!--使用package指定接口所在的包,只需resources下的Mapper.xml路径名称均和dao中的接口对应,则无需再写mapper和指定resource/class-->
<package name="com.company.dao"/>
</mappers>
</configuration>
IAcountMapper.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="com.company.dao.IAccountMapper">
<select id="findAll" resultType="com.company.domain.Account">
SELECT * FROM account
</select>
</mapper>
MyBatisTest.java
public static void main(String[] args) throws Exception {
//1.读取配置文件
InputStream in= Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂(构建者模式:隐藏对象的创建细节,使用者只需调用方法即可拿到对象)
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=builder.build(in);
-- (解析配置文件找到Driver,Url,Username,Password创建数据源,并找到Mapper文件)
//3.使用工厂对象获取SqlSession对象(工厂模式:创建对象的最佳方式,使用一个共同的接口来指向新创建的对象)
SqlSession session = factory.openSession();
-- (通过数据源获取连接)
//4.使用SqlSession对象创建Dao接口的代理对象(动态代理模式:不修改原有代码的情况下对已有方法进行增强)
IAccountMapper mapper = session.getMapper(IAccountMapper.class);
-- (通过接口获取代理对象,根据Mapper文件获取Sql和返回类型,添加执行、封装等实际运行的代码)
//5.使用代理对象执行方法
List<Account> all = mapper.findAll();
-- (执行方法获取结果)
System.out.println(all);
//6.释放资源
session.close();
in.close();
}