spring boot练习

修改pom.xml依赖:

com.mysql
mysql-connector-j
runtime

调整application.properties配置:

MySQL配置

spring.datasource.url=jdbc:mysql://localhost:3306/ku?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

JPA配置

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.format_sql=true

实体类调整建议(兼容MySQL)
@Entity
@Table(name = "blog_posts") // 显式指定表名
public class BlogPost {
// ...

@Column(length = 200) // 限制标题长度
@NotBlank(message = "标题不能为空")
private String title;
@Lob // 大文本字段注解
@Column(columnDefinition = "TEXT") // 显式定义字段类型
@NotBlank(message = "内容不能为空")
private String content;

// 其他字段保持不变

}

增强Service层(添加事务管理)
@Service
@Transactional
public class BlogService {
// 原有方法保持不变

public Page<BlogPost> getPostsPage(Pageable pageable) {
    return repository.findAllByOrderByCreateTimeDesc(pageable);
}

}

分页功能实现(Controller调整)
@GetMapping
public String listPosts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
Model model) {

Page<BlogPost> postPage = blogService.getPostsPage(PageRequest.of(page, size));
model.addAttribute("page", postPage);
return "posts/list";

}

Thymeleaf模板增强(分页导航)

posted @ 2025-03-11 21:57  老汤姆233  阅读(7)  评论(0)    收藏  举报