ssm框架增删改查代码
时间: 2024-01-06 22:25:20 浏览: 85
ssm框架增删改查
在SSM框架中,实现增删改查功能需要编写Controller、Service、Dao和Mapper四个部分的代码。下面是一个简单的示例:
1. 编写Controller层代码:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public String findAll(Model model) {
List<User> userList = userService.findAll();
model.addAttribute("userList", userList);
return "userList";
}
@RequestMapping("/add")
public String add(User user) {
userService.add(user);
return "redirect:/user/findAll";
}
@RequestMapping("/update")
public String update(User user) {
userService.update(user);
return "redirect:/user/findAll";
}
@RequestMapping("/delete")
public String delete(int id) {
userService.delete(id);
return "redirect:/user/findAll";
}
}
```
2. 编写Service层代码:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public void add(User user) {
userDao.add(user);
}
@Override
public void update(User user) {
userDao.update(user);
}
@Override
public void delete(int id) {
userDao.delete(id);
}
}
```
3. 编写Dao层代码:
```java
@Repository
public interface UserDao {
List<User> findAll();
void add(User user);
void update(User user);
void delete(int id);
}
```
4. 编写Mapper文件(UserDao.xml):
```xml
<mapper namespace="com.example.dao.UserDao">
<select id="findAll" resultType="com.example.entity.User">
SELECT * FROM user
</select>
<insert id="add" parameterType="com.example.entity.User">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<update id="update" parameterType="com.example.entity.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
```
以上代码示例演示了在SSM框架中实现增删改查功能的基本代码结构。你可以根据自己的需求进行修改和扩展。
阅读全文