IDEA使用Maven部署第一个MyBatis项目,两种方法导入,一个是Jar包的形式,此形式用于初学者学习并完成学校实训作业,第二种则是通过pom.xml文件引入依赖从而避免了从官网下载jar包等问题。
一、创建一个Maven工程:File-->New-->projcet-->Maven
二、导入以下Jar包:New-->Projcet Structure-->Modules-->Dependencies
三、打开DataGrip或者Navicat创建数据库,尝试着插入一些数据,请插入自己所需要测试的数据进行测试(省)
四、开始编写项目,整体项目文件结构如图:
1、在resources目录下建立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="jdbc.properties"/>
<environments default="mysql">
<environment id="mysql">
<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>
<mappers>
<mapper resource="mapper/UserMapper.xml" />
</mappers>
</configuration>
2、在resources目录下建立JDBC.properties文件和log4j.properties文件
# 数据库连接驱动类
driver=com.mysql.jdbc.Driver
# 数据库(mysql)连接字符串
url=jdbc:mysql://localhost:3306/sosorun?useUnicode=true&characterEncoding=UTF-8
# 数据库用户名
username=root
# 数据库密码
password=123456
#全局日志配置
log4j.rootLogger=ERROR, stdout
#Mybatis 日志配置
log4j.logger.com.hnsoft=DEBUG
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3、在com.hnsoft.pojo文件夹下创建User.java文件
package com.hnsoft.pojo;
public class User {
private Integer id;
private String userName;
private String passWord;
private String phone;
private int gender;
private int status;
private String addr;
private String photo;
private String birth;
private String email;
private int score;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", passWord=" + passWord +
", phone=" + phone + ", gender=" + gender + ", status=" + status +
", addr=" + addr + ", photo=" + photo + ", birth=" + birth +
", email=" + email + ", score=" + score + "]";
}
public User() {
super();
}
}
4、在com.hnsoft.mapper包下创建UserMapper.java接口类
并且在resources目录下创建mapper文件夹,mapper文件夹下创建UserMapper.xml映射文件。这里要特别注意mapper namespace的路径以及select id =应该等于的是UserMapper.java的各种方法不能出错
package com.hnsoft.mapper;
import com.hnsoft.pojo.User;
public interface UserMapper {
/**
* 通过用户名和密码查询用户
* @param uName
* @param pWord
* @return User对象
*/
User findUserByUNameAndPWord(String uName, String pWord);
/**
* 通过用户名查询用户数
* @param uName
* @return
*/
int findUserCountByUName(String uName);
/**
* 使用用户名和密码添加新游戏玩家
* @param uName
* @param pWord
* @param phone
* @param gender
* @return
*/
int addNewPlayerUser(String uName,String pWord, String phone, int gender);
}
<?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.hnsoft.mapper.UserMapper">
<!-- 通过用户名和密码查询用户 -->
<select id="findUserByUNameAndPWord" parameterType="String" resultType="com.hnsoft.pojo.User">
select * from t_user_info where uname = #{uName} and pword = #{pWord}
</select>
<select id="findUserCountByUName" parameterType="String" resultType="_int">
select COUNT(1) from t_user_info where uName=#{uName}
</select>
<insert id="addNewPlayerUser">
INSERT INTO t_user_info (uName, pWord, phone, gender, status, score)
VALUES (#{uName}, #{pWord}, #{phone}, #{gender}, 1, 1000);
</insert>
</mapper>
5、从mybatis-config.xml中创建SqlSessionFactory,因为每个MyBatis应用程序都围绕一个SqlSessionFactory的实例。可以使用SqlSessionFactory构建器获取SqlSessionFactory实例。所以我们创建com.hnsoft.utils文件夹,创建MybatisUtils.java
package com.hnsoft.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
// 读取mybatis核心配置文件
InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
// 构建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 静态单例会话
* @return
*/
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
6、划重点!在scr目录下,创建一个Test sources root的Java也就是绿色的Java文件夹,然后再这个Java下创建com.hnsoft.test.MybatisTest.java。为什么要这么做?是因为 IDEA 会自动为测试文件设置合适的类路径和资源加载方式。把测试类放Sources Root
中时,IDEA 可能无法正确处理这些资源,导致配置文件和映射文件加载失败,在我的2022idea版本中,如果我把这个测试类放在了sources root也就是蓝色的Java文件夹下,那么我将获取不到mybatis-config.xml,又因为mybatis-config.xml里面有,所以就是获取不到我指定的UserMapper.xml。他会报错!
<mapper resource="mapper/UserMapper.xml" />
7、测试运行
能够登录成功
如果要执行这一步操作,请点击Help-->Edit Custom Properties..输入
editable.java.test.console=true