Mybatis 环境项目搭建
Posted 闲言_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis 环境项目搭建相关的知识,希望对你有一定的参考价值。
前言
- 好久没写mybatis 了,今天写条博客 加深一些mybatis的 印象!
步骤一:创建maven 工程 导入mybatis 相关依赖
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis 包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
步骤二:创建实体类
/**
* @Classname User
* @Description 用户实体类
* @Date 2021/5/17 21:49
* @Created by 闲言
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String perms;
}
步骤三:创建Mapper 接口并添加方法
/**
* @Classname UserMapper
* @Description 用户mapper接口
* @Date 2021/5/17 21:50
* @Created by 闲言
*/
public interface UserMapper {
List<User> findAll();
}
步骤四:创建mapper 文件
- 注意:在resources 资源目录下创建和mapper 接口一样的层级路径
- 非必须
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.bloghut.mapper.UserMapper">
<select id="findAll" resultType="cn.bloghut.domain.User">
select * from user;
</select>
</mapper>
mapper接口包路径
mapper文件路径1
步骤五:编写mybatis 配置文件
<?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 name="cn.bloghut.domain.User"/>
</typeAliases>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="xx"/>
<property name="password" value="xx"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--指定mapper 文件的路径-->
<mapper resource="cn/bloghut/mapper/UserMapper.xml"/>
</mappers>
</configuration>
步骤六:测试
public class Test1 {
@Test
public void test1() throws Exception{
//加载配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//通过SqlSession工厂
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//获取SQLSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取代理的mapper 接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法,获取返回值
List<User> users = mapper.findAll();
for (User user : users) {
System.out.println(user);
}
}
}
以上是关于Mybatis 环境项目搭建的主要内容,如果未能解决你的问题,请参考以下文章
Maven 项目使用mybatis的环境搭建-基于xml形式实现查询所有的功能