2017-09-19 30 views
1

我遇到了一個持久對象的小問題。以下是我的實體類看起來像的一個例子。如何僅保存在spring crudrepository中分配的屬性?

@Entity 
public class Example(){ 
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    private Integer id; 
    private int number; 
    private String sentence; 
/* No arg const, getters and setters omitted */ 

CrudRepository接口:

@Repository 
public interface ExampleRepository extends CrudRepository<Example, Integer> 
{} 

服務實現接口:

@Service 
public class ExampleService{ 
    @Autowired 
    public ExampleRepository exampleRepository; 
    public void save(Example example){ 
     exampleRespository.save(example) 
    } 
} 

內CommandLineRunner的:

Example example1 = new Example(); 
example1.sentence("Hello World!"); 
exampleService.save(example1); 

現在我遇到問題是即使我沒有給屬性號賦值,它仍然會持續爲0.如何阻止該屬性被賦值爲0並使其爲空?

回答

0

變化

private int number; 

private Integer number; 
0

上述方案是好的,但如果再次在插入查詢看到你的保存功能,它插入所有3列,即使你只分配一次example1.sentence("Hello World!");

您可以使用@DynamicInsert(true)@DynamicUpdate(true)在實體級別, 這將觸發查詢爲

insert into example(sentence) values('Hello World!'); 

這樣的查詢性能將提高

+0

謝謝你的提示。我會記住這一點。 – Saurin