SpringBoot整合SpringMVC+Mybatis
- 配置pom.xml文件
- 添加application.properties 全局配置文件
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#给包下的实体类取别名
mybatis.type-aliases-package=com.steer.pojo
- 创建数据库与实体类
- 编写mapper接口以及映射配置文件
- 编写业务层
- 编写控制类
- 编写页面
1.在mapper接口上要添加@Component注解
2.在业务层实现类上添加@Service和@Transactional这两个注解
@Transactional将该公共类方法纳入事务管理
3.启动类上要添加别名扫描
@MapperScan("com.steer.mapper") //@MapperScan 用户扫描MyBatis的Mapper接口,这样在mapper.xml文件中,参数类型就不用写全地址(com.steer.pojo.users)了,直接写users就行了。
UsersMapper.java
@Component
public interface UsersMapper {
// 新增用户信息
void insUser(Users users);
// 查询所有用户信息
List<Users> selAllUser();
// 根据id查询用户信息
Users findUserById(Integer id);
// 修改选中的用户信息
void updUser(Users users);
//删除用户信息
void delUser(Integer id);
}
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.steer.mapper.UsersMapper">
<insert id="insUser" parameterType="users">
insert into users(name, age) values (#{name}, #{age})
</insert>
<select id="selAllUser" resultType="users">
select * from users
</select>
<select id="findUserById" parameterType="int" resultType="users">
select * from users where id=#{id}
</select>
<update id="updUser" parameterType="users">
update users set name=#{name}, age=#{age} where id=#{id}
</update>
<delete id="delUser" parameterType="int">
delete from users where id=#{id}
</delete>
</mapper>
UserServiceImpl.java
@Service
@Transactional
public class UsersServiceImpl implements UsersService {
@Autowired
private UsersMapper usersMapper;
@Override
public void addUser(Users users) {
this.usersMapper.insUser(users);
}
@Override
public List<Users> showAllUser() {
return this.usersMapper.selAllUser();
}
@Override
public Users findUserById(Integer id) {
return this.usersMapper.findUserById(id);
}
@Override
public void updUser(Users users) {
this.usersMapper.updUser(users);
}
@Override
public void delUser(Integer id) {
this.usersMapper.delUser(id);
}
}
网友评论