2016-03-01 138 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); 
相关问题