配置文件
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">
<!-- 配置mysql的环境 -->
<environment id="mysql">
<!-- 配置事务的类型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源(连接池)-->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/school"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<mapper resource="mapper/AccountDao.xml"/>
</mappers>
</configuration>
Mapper映射xml文件
AccountDao.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.superx.dao.AccountDao">
<!-- 配置查询所有 -->
<select id="findAll" resultType="com.superx.entity.Account">
select * from account
</select>
</mapper>
实体类
Account.java
/**
* @author
* @Date
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Account implements Serializable {
private static final long serialVersionUID=1L;
private Integer id;
private String name;
private double money;
private Integer version;
private Integer deleted;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
mapper接口
AccountDao.java
/**
* @author
* @Date
*/
public interface AccountDao {
List<Account> findAll();
}
测试类中实现查询
MybatisTest.java
/**
* @author
* @Date
*/
public class MybatisTest {
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 sqlSession = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
//5.使用代理对象执行方法
List<Account> list = accountDao.findAll();
for (Account account:list){
System.out.println(account);
}
//6.释放资源
sqlSession.close();
}
}
本文详细介绍了MyBatis框架的配置过程,包括SqlMapConfig.xml配置文件的解析,环境设置,事务管理,数据源配置,以及Mapper映射文件的使用。通过一个具体的例子,展示了如何在Java中使用MyBatis进行数据库操作。
300

被折叠的 条评论
为什么被折叠?



