MyBatis Idea配置步骤以及数据操作方法实例
写在前面的话:MyBatis B站的秦疆老师讲的很好,大家可以去学习一下,真的很推荐。搜的话搜的是:狂神说Java
MyBatis是干啥的也不再赘述,可以自行查阅文档
MyBatis3官方文档链接
一、创建Maven项目
删掉src作为父工程
项目结构如下
pom.xml导入依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!--父工程--> <groupId>com.lz</groupId> <artifactId>MyBatis0816</artifactId> <version>1.0-SNAPSHOT</version> <!--导入依赖--> <dependencies> <!--MySQL驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--mybatis--> <!-- https://mvnrepository. com/artifact/org. mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> <properties> <!-- 设置默认编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> </project>
相关驱动的引入就不再赘述,这里挑出来两点讲一下
1.为什么要写build
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
build里面的东西是为了读取src/main/resources中的xml文件的,如果不加可能会有not found xxx.xml的错误。
说回来,我们不是把父工程里的src删掉了吗?为什么还要配置呢,是为了保险起见,同样的在子工程的pom.xml
中我们也是需要加bulid的,就不再赘述。
2.为什么要设置默认编码
<properties> <!-- 设置默认编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
如果不写的话可能在代码运行起来之后,会出现一个第三字节什么什么的错误。同样的也要在子工程的pom.xml中加入
二、创建子项目
pom.xml导入build 和默认编码
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>MyBatis0816</artifactId> <groupId>com.lz</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>MyBatis01</artifactId> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> <properties> <!-- 设置默认编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> </project>
根据官方文档的引导,此时我们应该去配置xml文件,为什么要配置这个xml文件呢?因为MyBatis说白了,就是用来干JDBC的活的,
把JDBC的活给简化了。根据官方文档中说的,我们配置的这个xml文件相当于是SqlSessionFactoryBuilder,然后通过SqlSessionFactoryBuilder构造SqlSessionFactory实例,再通过SqlSessionFactory拿到SqlSession。一般的话,我们把这个xml文件叫
做mybatis-config.xml,前面配置的build就是为了读取这个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 核心配置文件--> <!--引入外部配置文件--> <configuration> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value=""/> </properties> <typeAliases> <package name="com.lz.pojo"/> </typeAliases> <!--environments 选择默认配置文件--> <environments default="test"> <environment id="development"> <!--在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")--> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/stu0807?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment> <environment id="test"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!--Mapper.xml需要在MyBatis核心配置文件中注册--> <mappers> <!--注册绑定mapper--> <!-- <mapper resource="com/lz/dao/UserMapper.xml"/>--> <!--使用class文件注册绑定--> <!--接口和mapper必须同名同包--> <!--<mapper class="com.lz.dao.UserMapper"/>--> <!--使用扫描包注册绑定--> <!--接口和mapper必须同名同包--> <package name="com.lz.dao"/> </mappers> </configuration>
属性的话可以通过外部配置或者内部配置
<!--引入外部配置文件--> <configuration> <properties resource="db.properties"> <property name="username" value="root"/> <property name="password" value=""/> </properties>
目录结构如下
外部配置内容如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/stu0807?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=
可以注意到我在db.properties文件中设置了username 和password,在mybatis-config.xml中也用property标签设置了
username和password,事实上在使用外部配置的情景下,只需要在上述两个地方中的一个设置就好了,如果都设置了,
那么db.properties中的设置是优先于mybatis-config.xml中property标签设置的。大家想验证这个结论的话可以试着将
db.properties中的密码改成错误的密码,看程序是否能正确运行。
需要注意的是此时还没完成使用外部文件配置,如果选用外部配置的话,还需要将一个环境的value与之对应起来
<environment id="test"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment>
因为MyBatis支持多套配置文件所以最后记得选用对应的配置文件
<!--environments 选择默认配置文件--> <environments default="test">
选择内部的配置文件的话配置如下,记得改默认配置。还有"&" == &
<environment id="development"> <!--在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")--> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/stu0807?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment>
完成上述工作后,
在该目录下完成SqlSessionFactory的实例化
代码如下:
public class MyBatisUtils { //相当于数据库连接池 private static SqlSessionFactory sqlSessionFactory; static { try { //获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //有了SqlSessionFactory,顾名思义,我们可以拿到SqlSession实例 //SqlSession 完全包含了面向数据库执行的SQL命令所需的所有方法 public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
我连的数据库里面有一张学生表,设计的不好,没有满足设计的范式,但是也能拿来学习,表的内容如下
然后我创建了对应的实体,因为当时比较懒,id我给的是自增长的,为了解决传参问题所以我多给了几个构造方法
代码如下
@Data //@Alias("green") public class User { private int id; private String name; private String _class; public User(String name, String _class) { this.name = name; this._class = _class; } public User(int id, String name, String _class) { this.id = id; this.name = name; this._class = _class; } public User() { } }
dao层的UseMapper接口提供了一些操作的方法
public interface UserMapper { //查询全部用户 List<User> getUserList(); List<User> getUserLike(String s); //根据ID查询用户 User getUserById(int id); User getUserById2(Map<String, Object> map); int addUser(User user); int addUser2(Map<String, Object> map); int upDateUser(User user); int deleteUser(int id); }
然后就是映射器mapper.xml了,mapper中写的就是我们的增删查改操作
<?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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.lz.dao.UserMapper"> <!--查询语句--> <!--id 对应的namespace方法名--> <select id="getUserList" resultType="user"> select * from stu0807.student; </select> <select id="getUserById" resultType="user" parameterType="int"> select * from stu0807.student where id = #{id}; </select> <!--<select id="getUserById2" resultType="com.lz.pojo.User" parameterType="map">
select * from stu0807.student where id = #{id};
</select>--> <insert id="addUser" parameterType="user"> insert into stu0807.student(name, _class) values (#{name},#{_class}); </insert> <!--<insert id="addUser2" parameterType="map">
insert into stu0807.student(name, _class) values (#{name},#{_class});
</insert>--> <update id="upDateUser" parameterType="user"> update stu0807.student set name = #{name}, _class = #{_class} where id = #{id}; </update> <delete id="deleteUser" parameterType="int"> delete from stu0807.student where id = #{id}; </delete> <!--<select id="getUserLike" resultType="com.lz.pojo.User">
select *from stu0807.student where name like #{name};
</select>--> </mapper>
namespace用来绑定对应操作所在的接口
<!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.lz.dao.UserMapper">
增删查改就不再赘述,要注意的一点是 resultType如果是自定义类,默认是需要写全路径的,如果不想写全路径,需要在mybatis-config.xml
中加入typeAliases标签,并且加的位置是有讲究的,如果你不知道具体的顺序,Idea会给你提示
我们可以看到typeAliases应该是在properties和settings后面的,因为我没写settings所以typeAliases应该是在properties后面的
typeAliases说白了就是给起别名
然后typeAliases有两种用法
<typeAliases> <!--<typeAlias alias="user" type="com.lz.pojo.User" />--> <package name="com.lz.pojo"/> </typeAliases>
一是typeAlias 标签,type后跟类名,alias后跟的是别名
二是package 标签,跟包名,别名是包名里类的小写如:User类,别名就是user,但是用User也是可以识别的。
如果你使用了package标签并且还想自己DIY的话,你可以在实体类的前面加个@Alias(“你想叫的别名”)注解,实现DIY。
完成了mapper.xml的编写后,记得要在mybatis-config.xml中注册
如下:
<!--Mapper.xml需要在MyBatis核心配置文件中注册--> <mappers> <!--注册绑定mapper--> <!-- <mapper resource="com/lz/dao/UserMapper.xml"/>--> <!--使用class文件注册绑定--> <!--接口和mapper必须同名同包--> <!--<mapper class="com.lz.dao.UserMapper"/>--> <!--使用扫描包注册绑定--> <!--接口和mapper必须同名同包--> <package name="com.lz.dao"/> </mappers>
三种大同小异的方法resource、class、package,但是需要注意的是,使用class和package方法的话
接口必须和mapper同名同包
最后可以来测试一下效果
代码如下:
public class UserDaoTest {
/*@Test
public void test() {
//1.获取SqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//方式一:getMapper
//UseDao useDao = sqlSession.getMapper(UseDao.class);
//List<User> userList = useDao.getUserList();
List<User> userList = sqlSession.selectList("com.lz.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}*/
/*@Test
public void getUserById() {
//1.获取SqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//方式一:getMapper
//UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//System.out.println(mapper.getUserById(3));
//List<User> userList = useDao.getUserList();
List<User> userList = sqlSession.selectList("com.lz.dao.UserMapper.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}*/
/*@Test
public void getUserById2() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("id",12);
System.out.println(mapper.getUserById2(map));
sqlSession.commit();
sqlSession.close();
}*/
/*@Test
public void addUser2() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name","map");
map.put("_class","一年级二班");
int ret = mapper.addUser2(map);
if(ret > 0) {
System.out.println("success");
}else {
System.out.println("fail");
}
sqlSession.commit();
sqlSession.close();
}*/
/* @Test
public void addUser() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int ret = mapper.addUser(new User("kdcbj", "三年级一班"));
if(ret > 0) {
System.out.println("success");
}else {
System.out.println("fail");
}
sqlSession.commit();
sqlSession.close();
}*/
/** @Test
public void update() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int ret = mapper.upDateUser(new User(10,"东风知我意", "六年级六班"));
if(ret > 0) {
System.out.println("success");
}else {
System.out.println("fail");
}
sqlSession.commit();
sqlSession.close();
}*/
/* @Test
public void deleteUser() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int ret = mapper.deleteUser(5);
if(ret > 0) {
System.out.println("success");
}else {
System.out.println("fail");
}
sqlSession.commit();
sqlSession.close();
}*/
public void isSuccess(int ret) {
if(ret > 0) {
System.out.println("success");
}else {
System.out.println("fail");
}
}
/*@Test
public void getUserLike() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.getUserLike("%小%");
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}*/
@Test
public void getUserList() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.getUserList();
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
}
执行效果如下(getUserList)
@Test public void getUserList() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> list = mapper.getUserList(); for (User user : list) { System.out.println(user); } sqlSession.close(); }
有些流程是固定的:第一步 创建sqlSession 实例,第二步创建mapper实例,执行sql,关闭 sqlSession
本文地址:https://blog.csdn.net/wobuyaoshiye/article/details/108033988
下一篇: CCF准备日记——202006-1