赞
踩
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。 MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
环境:idea2019,mysql8.0.25
准备工作:新建maven项目
项目目录结构:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.8</version> <scope>provided</scope> </dependency> <!-- 连接数据库的驱动--> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.0.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- 控制台打印日志信息--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-to-slf4j</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> </dependencies>
数据库表如图:
package com.mb1.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @NoArgsConstructor @AllArgsConstructor @ToString public class User01 { private int userId; private String username; private String password; private String email; public User01(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } }
位置在resources文件夹下。
数据库配置文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/book?spring&serverTimezone=GMT%2B8&useUnicode=true&characterEncodig=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123456
log4j.properties文件,用于日志的打印
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
用户映射文件UserMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mb1.map"> <select id="selectAll" resultType="com.mb1.pojo.User01"> select * from user </select> <select id="selectOne" resultType="com.mb1.pojo.User01" parameterType="int"> select * from user where userId=#{userId}; </select> <delete id="deleteById" parameterType="int"> delete from user where userId=#{userId} </delete> <insert id="insertUser" parameterType="com.mb1.pojo.User01"> insert into user(username,password,email) values(#{username},#{password},#{email}) </insert> <update id="updateUser" parameterType="com.mb1.pojo.User01"> update user set username=#{username} where userId=#{userId} </update> </mapper>
全局配置文件SqlMapperConfig.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"></properties> <!-- 环境DEV,代码开发环境--> <environments default="dev"> <environment id="dev"> <!-- Mybatis事务管理器--> <transactionManager type="JDBC"></transactionManager> <!-- 数据源POOLED用连接池,UNPOOLED,JNDI应用在EJB容器中--> <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> <mappers> <mapper resource="UserMapper.xml"></mapper> </mappers> </configuration>
package com.mb1.test; import com.mb1.pojo.User01; 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; import java.util.List; public class TestM1 { public static void main(String[] args) throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapperConfig.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession session = sessionFactory.openSession(true);//自动提交事务,否则无法持久化到数据库 ...//实现增删查改业务功能代码 } }
代码:
User01 user = new User01("add","123","333333@qq.com");
int count = session.insert("com.mb1.map.insertUser", user);
System.out.println(count);
运行截图:
代码:
int delete = session.delete("com.mb1.map.deleteById", 2);
System.out.println(delete);
运行截图:
代码:
//查找全部对象,只输出对象名
List<User01> user01List = session.selectList("com.mb1.map.selectAll",User01.class);
for(User01 u:user01List){
System.out.println(u.getUsername());
}
//根据id查找单个对象
User01 user01 = session.selectOne("com.mb1.map.selectOne", 4);
System.out.println("查找单个对象"+user01);
运行截图:
代码:
//根据用户id修改用户名
User01 user01 = new User01();
user01.setUserId(6);
user01.setUsername("update");
int update = session.update("com.mb1.map.updateUser", user01);
System.out.println(update);
运行截图:
namespace即空间命名名称,用于区分实现数据持久化的方式。namespace一般绑定对应的文件的全路径。详解:namespace用法
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。