2017-08-28 37 views
0

我正在使用Spring Boot創建一個簡單的博客應用程序,方法如下(不完整)教程:http://www.nakov.com/blog/2016/08/05/creating-a-blog-system-with-spring-mvc-thymeleaf-jpa-and-mysql/#comment-406107SpringHibernate - 爲一個簡單的博客應用程序設置mysql表

模型的實體類如下,郵政和用戶:

首先對郵政代碼:

@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數據庫腳本。

+0

也許我誤解了如何冬眠的作品。看起來好像我需要做的就是創建數據庫模式blog_db,並且提供了我的應用程序屬性是正確的,hibernate實例化表本身!哇...全新的真棒水平....猜測我回答了我自己的問題:)大聲笑... –

回答

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.Once你已經運行替換項目創建,更新或無這將避免表格的內在落差來創建新的表格。

spring.jpa.hibernate.ddl-auto=create 

如果您有任何疑問,下面的鏈接將是一個良好的開端

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

相關問題