2016-03-01 22 views
0

我正在使用Spring Boot和Spring Data JPA。我創建了一個實體作爲一個具有原型範圍的Spring bean。如何讓每個對象的bean保存在數據庫中?如何在Spring Boot中獲取Bean的原型

@Entity 
@Table(name="sample") 
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE) 
public class Sample { 
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private Long id; 

    private String name; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 

如果我不使用實體的Spring bean,然後我將使用下面的代碼來獲取對象:

Sample sample = new Sample(); 

我應該如何使用使用Spring中的原型範圍的bean對象啓動?

+0

您使用Spring並不意味着一切必須是一個Spring bean的事實。自己創建一個新實例沒有任何問題。 –

回答

0

你不想爲實體定義範圍。實體不像春豆。

Spring數據使用三個重要組件來保存到數據庫中。

1)實體類 - 每個表都必須定義自己的java對象模型,稱爲實體類。

@Entity 
@Table(name="sample") 
public class Sample { 
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private Long id; 

    @Column(name="name") //Column name from the table 
    private String name; 

2)Repo接口 - 您可以在其中定義自己的SQL實現,並且默認情況下會有保存方法。

public interface SampleRepo extends CrudRepository<Sample,Long>{ 
List<Sample> findByName(String name); 
} 

3)客戶端程序:

private SampleRepo s; 
//instantiate s using autowired setter/constructor 
.... 
//Select example 
List<Sample> sampleList=s.findByName("example"); 

//Insert example 
//Id is auto. So no need to setup explicit value for it. 
Sample entity=new Sample(); 
s.setName("Example"); 
s.save(entity); 
相關問題