下面就给您详细讲解“基于MyBatis的简单使用(推荐)”。
什么是MyBatis?
MyBatis是一款基于Java语言的开源持久层框架,它是面向SQL的框架,并且可以轻松地与各种数据源进行集成。它的主要特点是使得数据持久化开发变得更加容易,开发者只需要编写简单的SQL语句,而且框架还为开发者提供了便捷的ORM操作。
MyBatis的简单使用
下面我们来演示一下如何在Java项目中使用MyBatis。
- 首先需要引入MyBatis的相关依赖,常用的有以下五个:
<!--MyBatis核心依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--MyBatis与Spring集成依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--数据库连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.2</version>
</dependency>
<!--数据库驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!--日志依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
- 在项目的配置文件中配置数据库连接、MyBatis与Spring的集成、Mapper的扫描等信息。
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="1" />
<property name="maxActive" value="20" />
<property name="maxWait" value="60000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<property name="filters" value="mergeStat" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.example.model" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!--扫描MyBatis Mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper" />
</bean>
- 编写Mapper接口,用于执行SQL语句。
public interface UserMapper {
@Select("select * from t_user where id = #{id}")
User selectById(Long id);
@Select("select * from t_user")
List<User> selectAll();
@Insert("insert into t_user(username, password) values(#{username}, #{password})")
int insert(User user);
@Update("update t_user set username = #{username}, password = #{password} where id = #{id}")
int update(User user);
@Delete("delete from t_user where id = #{id}")
int deleteById(Long id);
}
- 编写Mapper映射文件,用于描述SQL语句的具体内容。
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="userMap" type="com.example.model.User">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="password" column="password" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
</resultMap>
<select id="selectById" resultMap="userMap">
select * from t_user where id = #{id}
</select>
<select id="selectAll" resultMap="userMap">
select * from t_user
</select>
<insert id="insert">
insert into t_user(username, password) values(#{username}, #{password})
</insert>
<update id="update">
update t_user set username = #{username}, password = #{password} where id = #{id}
</update>
<delete id="deleteById">
delete from t_user where id = #{id}
</delete>
</mapper>
- 编写Service层,调用Mapper接口执行SQL语句,并包装返回的结果。
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User selectById(Long id) {
return userMapper.selectById(id);
}
public List<User> selectAll() {
return userMapper.selectAll();
}
public void insert(User user) {
userMapper.insert(user);
}
public void update(User user) {
userMapper.update(user);
}
public void deleteById(Long id) {
userMapper.deleteById(id);
}
}
- 编写Controller层,对外提供接口。
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User selectById(@PathVariable Long id) {
return userService.selectById(id);
}
@GetMapping("")
public List<User> selectAll() {
return userService.selectAll();
}
@PostMapping("")
public void insert(@RequestBody User user) {
userService.insert(user);
}
@PutMapping("")
public void update(@RequestBody User user) {
userService.update(user);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id) {
userService.deleteById(id);
}
}
示例
下面给出基于MyBatis的两个示例。
- 查询用户信息
用户信息在t_user表中,包含id, username, password, create_time, update_time五个字段。根据用户id查询其信息。
public interface UserMapper {
@Select("select * from t_user where id = #{id}")
User selectById(Long id);
}
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User selectById(Long id) {
return userMapper.selectById(id);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User selectById(@PathVariable Long id) {
return userService.selectById(id);
}
}
- 新增用户信息
用户信息需要新增到t_user表中,包含id, username, password, create_time, update_time五个字段。需要通过Spring MVC接收用户提交的数据,并将数据保存到数据库。
public interface UserMapper {
@Insert("insert into t_user(username, password, create_time, update_time) values(#{username}, #{password}, #{createTime}, #{updateTime})")
int insert(User user);
}
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void insert(User user) {
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
userMapper.insert(user);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("")
public void insert(@RequestBody User user) {
userService.insert(user);
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于MyBatis的简单使用(推荐) - Python技术站