controller层service层,dao层mapper层之间是怎么调用的的,并写一个示例代码
时间: 2023-08-20 20:30:19 浏览: 72
在典型的Java Web应用程序中,Controller层负责接收并处理HTTP请求,Service层负责业务逻辑的处理,DAO层负责与数据库的交互。Mapper层是MyBatis框架中的一层,用于映射数据库表与Java对象之间的关系。
通常情况下,Controller层会调用Service层的方法来处理业务逻辑,Service层会调用DAO层的方法来操作数据库。Mapper层则是通过MyBatis框架自动调用与数据库交互的方法。
下面是一个简单的示例代码,演示了Controller层如何调用Service层,Service层如何调用DAO层,以及如何使用Mapper层进行数据库操作。
Controller层代码:
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
}
```
Service层代码:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Long id) {
return userMapper.selectByPrimaryKey(id);
}
}
```
DAO层代码:
```
@Repository
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
```
Mapper层代码:
```
<?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.example.mapper.UserMapper">
<resultMap id="userMap" type="com.example.entity.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
</resultMap>
<select id="selectByPrimaryKey" resultMap="userMap" parameterType="java.lang.Long">
SELECT id, username, password FROM user WHERE id = #{id,jdbcType=BIGINT}
</select>
</mapper>
```
在这个示例中,Controller层通过调用UserService的getUserById方法来获取一个用户对象。Service层则调用UserMapper的selectByPrimaryKey方法从数据库中获取用户数据。Mapper层则是通过配置XML文件来实现与数据库的交互。