java超快速入门(六):mybatis操作数据库
2021-03-16 本文已影响0人
自我De救赎
在项目中引入mybatis依赖
在pom.xml中添加依赖
<!--mybatis数据库框架,底层封装了jdbc-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
mybatis配置文件
在resource文件夹中创建一个xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!--使用mybatis配置标准格式-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置环境(可配置多个):默认:development环境-->
<environments default="development">
<!--配置开发环境的参数-->
<environment id="development">
<!--配置事务处理方式-->
<transactionManager type="JDBC"/>
<!--数据源-->
<dataSource type="POOLED">
<!--驱动-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--链接-->
<property name="url" value="jdbc:mysql://127.0.0.1:3306"/>
<!--用户-->
<property name="username" value="username"/>
<!--密码-->
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
</configuration>
使用mapper
首先我们先创建一个数据表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
接下来实现一个表的映射实体类
package com.sinbxeunha.josechan.entity;
public class User {
public int id;
public String username;
public String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int 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;
}
}
然后创建一个mappers包,用于存放mapper的xml文件
UserMapper.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.sinbxeunha.josechan.mappers.UserMapper">
<!--定义一个select语句,方法名为selectUsers,返回参数为List<com.sinbxeunha.josechan.entity.User>对象-->
<select id="selectUsers" resultType="com.sinbxeunha.josechan.entity.User">
select * from user;
</select>
<!--定义一个insert语句,入参为User对象,使用#{attribute_name}获取对象中的属性值-->
<insert id="save" parameterType="com.sinbxeunha.josechan.entity.User">
insert into user(username,password) value(#{username}, #{password});
</insert>
</mapper>
创建好mapper.xml文件后,需要把它配置到mybatis的配置文件中
<mappers>
<mapper resource="com/sinbxeunha/josechan/mappers/UserMapper.xml"></mapper>
</mappers>
由于com/sinbxeunha/josechan/mapper
目录不是maven项目的静态资源文件,mybatis没法直接读取到mapper文件,需要在pom.xml加入以下配置
<build>
<resources>
<!--指明该资源为静态资源,这里配置指`src/main/java`目录下的所有目录的所有xml都标记为静态资源-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build
使用mapper查询数据库分为四个步骤
//读取上面创建的mybatis配置文件
InputStream inputStream = JoseChan.class.getClassLoader().getResourceAsStream("Mybatis.xml");
//创建builder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//创建工厂
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//创建SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
有了SqlSession就可以执行mapper中定义的sql了
//User对象
User user = new User("用户名", "密码");
/**
* 执行定义的insert语句,
* 第一个参数为执行的方法,这里为即UserMapper.xml文件中定义的namespace下的save方法
* 第二个参数是xml文件中parameterType指定的类型,这里为User对象
*/
sqlSession.insert("com.sinbxeunha.josechan.mappers.UserMapper.save", user);
/**
* 提交事务,默认开启事务,所有增删改操作都必须提交/回滚
* 如果希望自动提交,在获取SqlSession对象时openSession方法中传true
* SqlSession sqlSession = sqlSessionFactory.openSession();
*/
sqlSession.commit()
将mybatis整合进spring
引入spring-mybatis依赖
<!-- mybatis-spring整合组件 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--springboot jdbc数据库可配置化,用来简化数据源的配置,和mybatis没关,顺便做了-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${springframework.version}</version>
</dependency>
配置数据源
//链接
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db
//用户名
spring.datasource.username=username
//密码
spring.datasource.password=password
//数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
//使用链接池,一共有pooled|unpooled|jndi三种模式
spring.datasource.type=org.apache.ibatis.datasource.pooled.PooledDataSource
创建mybatis配置类
package com.sinbxeunha.josechan.configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* 用于替换Mybatis.xml
*/
//声明该文件为配置文件
@Configuration
public class MybatisConfig {
//在容器中创建SqlSessionFactory
@Bean
public SqlSessionFactory sqlSessionFactory(@Autowired DataSource dataSource) throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
TransactionFactory transactionFactory = new SpringManagedTransactionFactory();
sqlSessionFactoryBean.setTransactionFactory(transactionFactory);
return sqlSessionFactoryBean.getObject();
}
}
创建Repository类,用于代替mapper.xml
package com.sinbxeunha.josechan.repository;
import com.sinbxeunha.josechan.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 替换UserMapper.xml
*/
//让spring自动扫描识别到该接口
@Repository
public interface UserRepository {
//声明一个select语句
@Select("select * from user;")
public List<User> selectUsers();
//声明一个insert语句
@Insert("insert into user(username,password) value(#{username}, #{password});")
public int save(User user);
}
设置mapper自动扫描,被扫描的接口将会在运行时动态创建接口的实现对象
//扫描repository包下的文件
@MapperScan({"com.sinbxeunha.josechan.repository"})
public class Application implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, new String[0]);
}
}
接下来就可以使用mapper了,默认情况下,事务是未开启的,sql会自动提交,如果需要使用事务,使用@Transactional注解
//当该方法抛出异常时,执行回滚sql
@Transactional(rollbackFor={Exception.class})
public String createUser(String username, String password) throws Throwable {
User user = new User(username, password);
userRepository.save(user);
return "success";
}
2021-03-17日更新
上面新增用户时,使用了new来创建User对象,在spring中,我们应该把对象的创建交给容器,因此接下来我们修改一下代码,使用容器来创建User对象
在需要创建对象的类中注入容器
想要通过容器创建对象,首先我们要先获得容器,我们继承ApplicationContextAware,并且实现setApplicationContext方法,容器会在创建该类时,将容器传递给该类
@Controller
@RequestMapping({"/index"})
public class IndexController implements ApplicationContextAware {
@Autowired
public UserRepository userRepository;
public ApplicationContext applicationContext;
@RequestMapping({"/createUser"})
@ResponseBody
//当该方法抛出异常时,执行回滚sql
@Transactional(rollbackFor={Throwable.class})
public String createUser(String username, String password) throws Throwable {
User user = new User(username, password);
userRepository.save(user);
return "success";
}
/**
* 注入容器
* @param applicationContext
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
将User映射实体创建到容器中
这里使用原型模式创建对象,注意,代理模式需要不使用代理,否则getter方法无法获取到set进去的属性值
package com.sinbxeunha.josechan.entity;
@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.NO)
public class User {
public int id;
public String username;
public String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
}
//getter/setter...
}
从容器中获取User对象
接下来改造一下createUser方法
//当该方法抛出异常时,执行回滚sql
@Transactional(rollbackFor={Exception.class})
public String createUser(String username, String password) throws Throwable {
//User user = new User(username, password);
//使用容器获得User对象
User user = this.applicationContext.getBean(User.class);
user.setUsername(username);
user.setPassword(password);
userRepository.save(user);
return "success";
}