SpringHibernate - 为简单博客应用程序

时间:2017-08-28 22:02:13

标签: mysql spring hibernate spring-mvc spring-boot

我正在使用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;
}

这是User的代码:

@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;
}

请注意,为方便起见,我省略了package,imports和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,所以我没有取得任何成功。 (tut作者未能提供db脚本,因此我正在尝试重新创建它。)

我希望有人愿意帮我解决mysql数据库脚本问题。

1 个答案:

答案 0 :(得分:1)

确保您的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

如果您有任何疑问,以下链接将是一个良好的开端

https://spring.io/guides/gs/accessing-data-mysql/