利用Maven创建Mybatis项目并运行
一、创建项目
1、Create new Project 项目
2、选择Maven
3、填充GroupId和ArtifactId
4、完成后,创建Maven项目如下图
我们可以在里面创建实体类、测试类、接口类所在的包,为了后续的方便可以参考我是如何创建的,创建好之后是这个样子
二、导入Mybatis和MySQL需要的jar包
因为我们创建的是Maven项目,我们只需要在pom文件里面导入相应的依赖,
2.1、代码如下
<dependencies>
<!--mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!--mysql的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
2.2、添加之前的结构如同所示:点击 右下角-》 Import Changes
2.3点击 右下角-》 Import Changes 导入所需要的jar包;
三、添加实体Bean
四. 为实体类配置数据库信息(Student类与student表的映射)
4.1 我们首先创建mybatis数据库(也可以自己起名字)在该数据库下面创建student表,命令字符创建代码:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(10) NOT NULL auto_increment,
`name` varchar(10) NOT NULL,
`age` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gbk;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `t_student` VALUES ('1', '赵刚', '20');
INSERT INTO `t_student` VALUES ('2', '张三', '23');
INSERT INTO `t_student` VALUES ('3', '李四', '35');
如下图所示:
到这里我们的Student类和student的表的映射已经创建好了
4.2 接着在resources下面创建一个config.properties文件,用来存放我们的数据库的信息:
到这里我们已经配置好数据库了
5. 创建实体类的mapper映射文件(StudentMapper接口以及StudentMapper.xml可以理解为接口的实现)
5.1 、在mapper下面创建StudentMapper
在resources/mapper下面创建StudentMapper.xml(可以理解为StudentMapper的实现)
如下图所示:
5.2 创建StudentMapper.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.cgtn.mapper.StudentMapper">
<!--getStudent得到实现,增删改查都可以在mapper标签内进行实现,我们这里是查询所以学生-->
<select id="getStudent" parameterType="long" resultType="com.cgtn.entity.Student">
select id, name, age
from student
where id = #{id}
</select>
</mapper>
有可能会有不知道怎么创建StudentMapper.xml文件(这里简单的介绍一下,因为下面还需要创建mybatis-config.xml文件,知道如何创建的可以跳过这一部分)
首先进入:
File->Setting->File and code templates
代码模板如下:
<?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.HaiMeng.mapper.StudentMapper">
<!--getStudent得到实现,增删改查都可以在mapper标签内进行实现,我们这里是查询所以学生-->
<select id="getStudent" parameterType="long" resultType="com.HaiMeng.entity.Student">
select id, name, age
from student
where id = #{id}
</select>
</mapper>
这个时候我们再去点击新建,我们就会发现我们有一个这样的模板,再以后需要的时候就可以快速的创建,只需要再mapper标签内对接口里面的方法进行实现就可。
到此StudentMapper和StudentMapper.xml文件都创建完。
6. 配置Mybatis文件(文件名字可以命名为:mybatis-config.xml)
在resources下面创建mybatis-config.xml文件
mybatis-config.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>
<properties resource="config.properties"/>
<typeAliases>
<package name=""/>
</typeAliases>
<!-- 配置环境-->
<environments default="mysql">
<!-- 配置MySQL的环境-->
<environment id="mysql">
<!-- 配置事务的类型-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 配置连接数据库的四个基本信息-->
<property name="driver" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射文件的位置,映射文件指的是每个DAO独立的配置文件-->
<mappers>
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>
到这里,mybatis-config.xml就配置好.
7. 创建SqlSessionFactory工厂类(这是为了读取配置文件,执行sql语句,并且可以减少代码的冗余)
在utils下面创建SqlSessionFactory工厂类,代码如下
package com.HaiMeng.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactory {
private final static Class<SqlSessionFactory> lock= SqlSessionFactory.class;
private static org.apache.ibatis.session.SqlSessionFactory sqlSessionFactory=null;
private SqlSessionFactory(){};
//会话工厂
public static org.apache.ibatis.session.SqlSessionFactory getSqlSessionFactory() {
//
synchronized (lock) {
if (sqlSessionFactory != null) {
return sqlSessionFactory;
}
// mybatis配置文件的名字
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
//读取配置文件
inputStream = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
}
//使用工厂生产Sqlsession对象
public static SqlSession openSqlSession(){
if (sqlSessionFactory==null){
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
如下图所示:
8. 运行测试
在test/java下面创建测试类TestMybatis进行测试,代码如下:
在utils下面创建SqlSessionFactory工厂类,代码如下
import com.cgtn.mapper.StudentMapper;
import com.cgtn.utils.SqlSessionFactory;
import org.apache.ibatis.session.SqlSession;
public class TestMybatis {
public static void main(String[] args){
SqlSession sqlSession= SqlSessionFactory.openSqlSession();
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
System.out.println(studentMapper.getStudent(1).toString());
}
}
至此,运行成功!