先参考文章:【Spring MVC】使用IDEA创建Spring MVC的Maven项目 ,创建 Spring MVC 项目。
MyBatis最大的特点是:只需要写好 针对实体类映射数据库表的接口,不需要写接口的实现,MyBatis动态完成接口的实现。
MyBatis完成Java实体类和数据库表的ORM映射,主要有两种方式,一种是基于注解的;另外一种是基于XXXMaper.xml,用xml文件装配SQL,MyBatis动态实现接口的Impl,自动加载到Spring IoC容器,Controller在需要时即可
@Autowired
,本教程就是用第二种方式,实现最简单的User实体类与数据库表的映射,完成增删改查。
1、在Maven中添加“MySQL操作 相关依赖”:
<!--++++++++++++++++++++++++++++++++++++++++++++++++++++--> <!-- MySQL操作 相关依赖 --> <!--++++++++++++++++++++++++++++++++++++++++++++++++++++--> <!-- MySQL JDBC驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <!-- DAO框架:MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency>
2、在 applicationContext.xml 中加入内容:
<!--++++++++++++++++++++++++++++++++++++++++++++++++++++--> <!-- MyBatis配置 --> <!--++++++++++++++++++++++++++++++++++++++++++++++++++++--> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${driver}" p:jdbcUrl="${url}" p:user="${username}" p:password="${password}" p:idleConnectionTestPeriod="${idleConnectionTestPeriod}" p:maxIdleTime="${maxIdleTime}" p:acquireIncrement="${acquireIncrement}" p:initialPoolSize="${initialPoolSize}" p:maxPoolSize="${maxPoolSize}" p:minPoolSize="${minPoolSize}" p:autoCommitOnClose="${autoCommitOnClose}" p:checkoutTimeout="${checkoutTimeout}" p:acquireRetryAttempts="${acquireRetryAttempts}" p:preferredTestQuery="SELECT 1" p:maxConnectionAge="3000"/> <!-- MyBatis文件配置,扫描所有mapper文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="typeAliasesPackage" value="com.jianbao.entity"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- Spring与MyBatis整合配置,扫描所有DAO,指定的映射器类是接口, 接口方法可以用注解来指定SQL语句,但是MyBatis的映射器也可以用XML文件 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.jianbao.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory"/> <!-- 使用@Transactional进行声明式事务管理需要声明下面这行 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> <property name="rollbackOnCommitFailure" value="true"/> </bean>
3、新建文件:/src/main/resources/jdbc.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/java_web?useUnicode=true&useSSL=false&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&autoReconnect=true&serverTimezone=Asia/Shanghai username=root password=123456 idleConnectionTestPeriod=60 maxIdleTime=240 acquireIncrement=5 initialPoolSize=10 maxPoolSize=30 minPoolSize=10 autoCommitOnClose=false checkoutTimeout=1000 acquireRetryAttempts=2
4、新建文件:/src/main/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> <!-- mybatis全局设置 --> <settings> <!--使用数据库自增id--> <setting name="useGeneratedKeys" value="true"/> <setting name="useColumnLabel" value="true"/> <!-- 开启驼峰命名规范--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
5、创建实体文件:/src/main/java/com/jianbao/entity/User.java
package com.jianbao.entity; public class User { private Integer id; private String user_name; private String password; private String email; private String add_time; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return user_name; } public void setUserName(String userName) { this.user_name = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddTime() { return add_time; } public void setAddTime(String addTime) { this.add_time = addTime; } public String toString() { return "User{" + "id=" + id + ", user_name=" + user_name + ", password=" + password + "}"; } }
6、新建 Mapper 接口文件:/src/main/java/com/jianbao/dao/UserDao.java
package com.jianbao.dao; import com.jianbao.entity.User; import java.util.List; /** * DAO接口,MyBatis动态完成Impl(接口实现) */ public interface UserDao { Integer addUser(User u); Integer deleteById(Integer id); User findByUserName(String userName); User findById(Integer id); List<User> getUserList(); }
7、新建 Mapper 配置文件:/src/main/resources/mapper/userDao.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jianbao.dao.UserDao"> <insert id="addUser" parameterType="com.jianbao.entity.User"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT last_insert_id() </selectKey> INSERT INTO user(user_name, password, email) VALUE (#{userName}, #{password}, #{email}) </insert> <delete id="deleteById" parameterType="java.lang.Integer"> DELETE FROM user WHERE id=#{id} </delete> <select id="findById" parameterType="java.lang.Integer" resultType="com.jianbao.entity.User"> SELECT * FROM user WHERE id=#{id} </select> <select id="findByUserName" parameterType="java.lang.String" resultType="com.jianbao.entity.User"> SELECT * FROM user WHERE user_name=#{userName} </select> <select id="getUserList" resultType="com.jianbao.entity.User"> SELECT * FROM user </select> </mapper>
8、新建控制器文件:/src/main/java/com/jianbao/controller/UserController.java
package com.jianbao.controller; import com.jianbao.dao.UserDao; import com.jianbao.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @Autowired(required = true) private UserDao userDao; @RequestMapping(value = "/index", method = RequestMethod.GET) @ResponseBody public String index() { User user = userDao.findByUserName("wjb"); System.out.println(user); return "ok"; } @RequestMapping(value = "list", method = RequestMethod.GET) @ResponseBody public String userList() { List<User> userList = userDao.getUserList(); System.out.println(userList); return "ok"; } @RequestMapping(value = "/add", method = RequestMethod.GET) @ResponseBody public String save(@RequestParam("userName") String userName, @RequestParam(value = "password", defaultValue = "123456") String password, @RequestParam(value = "email", defaultValue = "phpjava8642@163.com") String email) { // 添加用户 User user = new User(); user.setUserName(userName); user.setPassword(password); user.setEmail(email); userDao.addUser(user); User userNew = userDao.findById(user.getId()); System.out.println(userNew); return "ok"; } @RequestMapping(value = "/delete", method = RequestMethod.GET) @ResponseBody public String delete(@RequestParam("id") Integer id) { userDao.deleteById(id); return "ok"; } }
9、项目目录结构截图
参考: