使用Spring+SpringMVC+Mybatis实现留言板的增删改查
以下是一个简化的例子,展示了如何使用Spring、Spring MVC和MyBatis实现一个留言板的基本功能。
- 创建数据库表:
CREATE TABLE `message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` varchar(255) NOT NULL,
`create_time` datetime NOT NULL,
PRIMARY KEY (`id`)
);
- 创建Message实体类:
public class Message {
private Integer id;
private String content;
private Date createTime;
// 省略getter和setter方法
}
- 创建MessageMapper接口:
@Mapper
public interface MessageMapper {
int insertMessage(Message message);
int deleteMessage(Integer id);
int updateMessage(Message message);
List<Message> selectAllMessages();
Message selectMessageById(Integer id);
}
- 创建MessageMapper.xml文件:
<mapper namespace="MessageMapper">
<insert id="insertMessage">
INSERT INTO message(content, create_time) VALUES(#{content}, #{createTime})
</insert>
<delete id="deleteMessage">
DELETE FROM message WHERE id = #{id}
</delete>
<update id="updateMessage">
UPDATE message SET content = #{content}, create_time = #{createTime} WHERE id = #{id}
</update>
<select id="selectAllMessages" resultType="Message">
SELECT * FROM message
</select>
<select id="selectMessageById" resultType="Message">
SELECT * FROM message WHERE id = #{id}
</select>
</mapper>
- 配置Spring和MyBatis:
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/your_database"/>
<property name="username" value="your_username"/>
<property name="password" value="your_password"/>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:MessageMapper.xml"/>
</bean>
<!-- 配置Mapper接口扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yourpackage.mapper"/>
</bean>
- 创建MessageController:
@Controller
@RequestMapping("/messages")
public class MessageController {
@Autowired
private MessageMapper messageMapper;
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
评论已关闭