Difference between @GeneratedValue and @GenericGenerator

后端 未结 3 998
不知归路
不知归路 2020-12-04 13:24

Sometimes I find them together, sometimes alone... other times they seem to do the same.

What\'s the difference?

Here are three examples. What do they do of

3条回答
  •  失恋的感觉
    2020-12-04 13:39

    @Entity
    @Table(name="Honey")
    public class Honey implements Serializable{
        private static final long serialVersionUID = 42L;
        @Id
        //@SequenceGenerator(name="honeySequence",sequenceName="HONEY_SEQ")
        @org.hibernate.annotations.GenericGenerator(name="honeySequence", strategy = "sequence", 
        parameters = { 
                @Parameter(name="sequence", value="HONEY_SEQ") } 
        )
        @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="honeySequence")
        private int Id;
        private String name;
        private String taste;
    
    • @GeneratedValue is used only to get the generated value. The two arguments strategy and generator are used to define how the value is obtained.
    • @GenericGenerator is used to map a user defined sequence generator with your hibernate session.
    • You can also use @SequenceGenerator which i have commented in my code. This is not a simple sequence generator but a generator which work on HILO algorithm. Due to which you will find a lot of gaps in your sequence, like your first value will start from 50 because the default allocation size is 50.

    So its better to use @GenericGenerator for your own architecture. But if you are bound to use @SequenceGenerator you have to manually edit your sequence to have two more attributes allocationSize=1 and initialValue=1. And to work with these attributes you need to add apropert in your hibernate.cfg.xml file

    true
    

提交回复
热议问题