码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis入门

时间:2020-03-06 11:08:59      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:细节   释放   artifact   resources   property   ESS   bat   row   oct   

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>
<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/company/dao/IAcountMapper.xml"></mapper>
</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);
//3.使用工厂对象获取SqlSession对象(工厂模式:创建对象的最佳方式,使用一个共同的接口来指向新创建的对象)
SqlSession session = factory.openSession();
//4.使用SqlSession对象创建Dao接口的代理对象(动态代理模式:不修改原有代码的情况下对已有方法进行增强)
IAccountMapper mapper = session.getMapper(IAccountMapper.class);
//5.使用代理对象执行方法
List<Account> all = mapper.findAll();
System.out.println(all);
//6.释放资源
session.close();
in.close();
}

Mybatis入门

标签:细节   释放   artifact   resources   property   ESS   bat   row   oct   

原文地址:https://www.cnblogs.com/zou-rong/p/12425025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!