Mybaits基本使用
整体的项目逻辑
第一步:配置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>
<!--
注意:MyBatis核心配置文件中的标签必须要按照指定的顺序配置:
(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)
-->
<!--引入Properties文件,此后就可以在当前文件中使用${key}的方式访问value-->
<properties resource="jdbc.properties"/>
<!--类型别名
typeAliases:设置类型别名,即为某个具体的类型设置一个别名。
在MyBatis的范围中,就可以使用别名表示一个具体的的类型
-->
<typeAliases>
<!--
type:设置需要起别名的类型
alias:设置某个类型的别名
-->
<!-- <typeAlias type="com.wfy.pojo.User" alias="User"></typeAlias>-->
<!--在不设置alias的前提下,其会存在一个默认的别名就是他的实体类类名,并且不区分大小写-->
<!-- <typeAlias type="com.wfy.pojo.User"></typeAlias>-->
<!--通过包设置类型别名,指定包下所有的类型将全部拥有默认的别名,即类名且不区分大小写 -->
<package name="com.wfy.pojo"/>
</typeAliases>
<!--配置连接数据库的环境-->
<!--
environments:配置连接数据库的环境
default:设置默认使用的环境的id
-->
<environments default="development">
<!--
environment:设置一个具体的连接数据库的环境
属性:
id:设置环境的唯一标识,不能重
-->
<environment id="development">
<!--
transactionManager:设置事务管理器
属性:
type:设置事务管理的方式
type=“JDBC/MANAGED”
JDBC:表示使用JDBC中原生的事务管理方式
MANAGED:被管理
-->
<transactionManager type="JDBC"/>
<!--
dataSource:设置数据源
属性:
type:设置数据源类型
type=“POOLED/UNPOOLED/JNDI”
POOLED:表示使用数据库连接池
UNPOOLED:表示不使用数据库连接池
JNDI:表示使用上下文中的数据源
-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入Mybatis的映射文件-->
<mappers>
<!-- <mapper resource="com/wfy/mapper/UserMapper.xml"/>-->
<!--
以包的方式引入映射文件,但是必须满足两个条件:
1.mapper接口和映射文件所在的包必须保持一致
2.mapper接口的名字和映射文件的名字必须保持一致
-->
<package name="com.wfy.mapper"/>
</mappers>
</configuration>
<?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.wfy</groupId>
<artifactId>mybatis-01-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>jar</packaging>
<dependencies>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!--log4j日志功能-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--mybatis控制台乱码问题的解决方案-->
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jboss-vfs</artifactId>
<version>3.2.16.Final</version>
</dependency>
</dependencies>
</project>
配置log4j日志文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM
"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration debug="false" >
<appender name="myConsole" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd HH:mm:ss,SSS\} %-5p] [%t] %c{2\} - %m%n"/>
</layout>
<!--过滤器设置输出的级别-->
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="debug" />
<param name="levelMax" value="warn" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<appender name="myFile" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="D:/dubbo/logs/provider/rollingLog/dubbo.log" /><!-- 设置日志输出文件名 -->
<!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->
<param name="Append" value="true" />
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%p (%c:%L)- %m%n" />
</layout>
</appender>
<appender name="activexAppender" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="D:/dubbo/logs/provider/dailyLog/dubbo.log" />
<param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{MMdd HH:mm:ss SSS\} %-5p] [%t] %c{3\} - %m%n" />
</layout>
</appender>
<!-- 指定logger的设置,additivity指示是否遵循缺省的继承机制-->
<logger name="com.runway.bssp.activeXdemo" additivity="false">
<appender-ref ref="activexAppender" />
</logger>
<!-- 根logger的设置-->
<root>
<priority value ="debug"/>
<appender-ref ref="myConsole"/>
<appender-ref ref="myFile"/>
</root>
</log4j:configuration>
创建数据库,配置0proprties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=root
如果时sql8则需要手动配置时区,不然会报bug
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTime=UTC
jdbc.username=root
jdbc.password=root
/*
Navicat Premium Data Transfer
Source Server : Mybatis
Source Server Type : MySQL
Source Server Version : 50528
Source Host : localhost:3306
Source Schema : ssm
Target Server Type : MySQL
Target Server Version : 50528
File Encoding : 65001
Date: 16/10/2022 21:45:05
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`age` int(10) NOT NULL,
`gender` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '任凌飞', '123456', 20, '男', '[email protected]');
INSERT INTO `user` VALUES (3, '绫小路清隆', '224466', 20, '男', '[email protected]');
INSERT INTO `user` VALUES (4, '任凌飞', '123456', 20, '男', '[email protected]');
SET FOREIGN_KEY_CHECKS = 1;
第二步:创建实体类和mapper接口
package com.wfy.pojo;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
private String email;
public User() {
}
public User(Integer id, String username, String password, Integer age, String gender, String email) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.gender = gender;
this.email = email;
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
}
package com.wfy.mapper;
import com.wfy.pojo.User;
import java.util.List;
public interface UserMapper {
int AddUser(User user);
int UpdateUser(User user);
int DeleteUser(int id);
List<User> SelectUser(int id);
List<User> SelectAllUsers();
}
第三步:在Resources目录下创建mapper的映射文件
通过映射文件实现对数据库的CURD
<?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.wfy.mapper.UserMapper">
<!--
mapper接口和映射文件要保证两个一致:
1.mapper接口的全类名和映射文件的namespace保持一致
2.mapper接口中的方法的方法名要和映射文件的sql的id保持一致
-->
<insert id="AddUser" >
insert into user values(null,#{username},#{password},#{age},#{gender},#{email})
</insert>
<update id="UpdateUser">
update user set username=#{username},password=#{password},age=#{age},email=#{email} where id=#{id}
</update>
<delete id="DeleteUser">
delete from user where id=#{id}
</delete>
<!--
resultType:设置结果类型,即查询的数据要转换为的java类型
resultMap:自定义映射,处理多对一或一对多的映射文件
-->
<select id="SelectUser" resultType="User">
select * from user where id=#{id}
</select>
<select id="SelectAllUsers" resultType="User">
select * from user
</select>
</mapper>
第四步:代码测试
为了简化注册驱动的代码,编写工具类实现Sqlsession
package com.wfy.util;
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.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtils {
public static SqlSession getSqlSession(){
SqlSession sqlSession=null;
try {
//获取核心配置文件的输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder SqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
//获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryBuilder.build(inputStream);
//获取SqlSession对象
sqlSession= sqlSessionFactory.openSession(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
return sqlSession;
}
}
测试代码:
package com.wfy.mybatis.test;
import com.wfy.mapper.UserMapper;
import com.wfy.pojo.User;
import com.wfy.util.SqlSessionFactoryUtils;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void AddUserTest() throws IOException {
//获取核心配置文件的输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder SqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryBuilder.build(inputStream);
//获取sql的会话对象SqlSession,SqlSession是Mybatis提供的对数据库的操作对象
// SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
//获取UserMapper的代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//封装对象
User user = new User();
String username="任凌飞";
String password="123456";
int age=20;
String gender="男";
String email="[email protected]";
user.setUsername(username);
user.setPassword(password);
user.setAge(age);
user.setGender(gender);
user.setEmail(email);
//调用mapper接口中的方法,实现添加用户信息的操作
int i = mapper.AddUser(user);
//提交事务,关闭资源
// sqlSession.commit();
sqlSession.close();
if (i>0){
System.out.println("添加成功~");
}else {
System.out.println("添加失败~");
}
}
@Test
public void UpdateTest(){
//获取SqlSession
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
//获取UserMapper代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int id=3;
User user=new User();
user.setUsername("绫小路清隆");
user.setPassword("224466");
user.setEmail("[email protected]");
user.setGender("男");
user.setAge(20);
user.setId(id);
int i = mapper.UpdateUser(user);
sqlSession.close();
if(i>0){
System.out.println("更新数据成功~");
}else {
System.out.println("更新数据失败~");
}
}
@Test
public void DeleteUser(){
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int id=5;
int i = mapper.DeleteUser(id);
if (i>0){
System.out.println("删除成功~");
}else {
System.out.println("删除失败~");
}
}
@Test
public void SelectUser(){
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int id=1;
List<User> users = mapper.SelectUser(id);
for (User user:users
) {
System.out.println(user);
}
}
@Test
public void SelectAllTest(){
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.SelectAllUsers();
users.forEach(System.out::println);
}
}
标签:基本,String,id,Mybaits,user,使用,import,password,public
From: https://www.cnblogs.com/wfy-studying/p/16811720.html