springboot中dao
时间: 2023-07-02 17:07:41 浏览: 125
在Spring Boot中,Dao(Data Access Object)层是与数据库进行交互的层。Dao层主要负责数据的持久化和访问,并且提供了一些接口给Service层调用。在Dao层中,通常使用JdbcTemplate或者MyBatis等持久化框架来访问数据库。
使用JdbcTemplate时,可以在Dao层中编写SQL语句来进行数据库操作。例如:
```java
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public User getUserById(int id) {
String sql = "SELECT * FROM user WHERE id = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
}
@Override
public void saveUser(User user) {
String sql = "INSERT INTO user(name, age) VALUES(?, ?)";
jdbcTemplate.update(sql, user.getName(), user.getAge());
}
// other methods...
}
```
如果使用MyBatis,则需要编写Mapper接口和对应的XML文件。例如:
```java
@Repository
public interface UserDao {
User getUserById(int id);
void saveUser(User user);
// other methods...
}
```
```xml
<!-- UserDao.xml -->
<mapper namespace="com.example.dao.UserDao">
<resultMap id="userMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<select id="getUserById" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="saveUser">
INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
<!-- other statements... -->
</mapper>
```
阅读全文