我正在使用 Spring Boot 创建一个简单的博客应用程序,方法是遵循(不完整的)教程:http://www.nakov.com/blog/2016/08/05/creating-a-blog-system-with-spring-mvc-thymeleaf-jpa-and-mysql/#comment-406107 .
模型实体类如下,Post和User:
首先是 Post 的代码:
@Entity
@Table(name="posts")
public class Post {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(nullable=false, length = 300)
private String title;
@Lob @Column(nullable=false)
private String body;
@ManyToOne(optional=false, fetch=FetchType.LAZY)
private User author;
@Column(nullable = false)
private Date date = new Date();
public Post() {
}
public Post(long id, String title, String body, User author) {
this.id = id;
this.title = title;
this.body = body;
this.author = author;
}
这是用户的代码:
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(nullable=false, length=30, unique=true)
private String username;
@Column(length=60)
private String passwordHash;
@Column(length=100)
private String fullName;
@OneToMany(mappedBy="author")
private Set<Post> posts = new HashSet<>();
public User() {
}
public User(Long id, String username, String fullName) {
this.id = id;
this.username = username;
this.fullName = fullName;
}
请注意,为了方便起见,我省略了包、导入和 getter/setter。
为了以防万一,我添加了我的 application.properties 文件:
spring.thymeleaf.cache = false
server.ssl.enabled=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/blog_db
spring.datasource.username=root
spring.datasource.password=somepassword
#Configure Hibernate DDL mode: create/update
spring.jpa.properties.hibernmate.hbm2ddl.auto=update
我想为我的代码创建一个相应的数据库,以连接到使用 mysql 社区服务器(更具体地说,工作台),并且由于我完全不熟悉 mysql,所以我没有取得任何成功。 (图特作者未能提供数据库脚本,因此我正在尝试重新创建它)。
我希望有人愿意帮助我编写 mysql 数据库脚本。
最佳答案
确保您的 pom.xml 中有所需的依赖项
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
不要忘记将此行添加到您的 application.properties 中。运行项目后,将 create 替换为 update 或 none,这将避免创建新表时固有的删除表的情况。
spring.jpa.hibernate.ddl-auto=create
如果您有任何疑问,以下链接将是一个好的开始
关于mysql - Spring Hibernate - 为简单的博客应用程序设置 mysql 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45927923/