views:

83

answers:

2
    @Entity
    @Table(name = "your_entity")
    public class YourEntityClass implements IEntity<Long> {

        @Id
        @SequenceGenerator(name = "gen_test_entity2_id", sequenceName = "test_entity2_id_seq", allocationSize = 10)
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen_test_entity2_id")
        private Long id;

        @Column(name = "name", nullable = false, length = 64)
        private String name;

        /*
         * Create constructors, getters, setters, isEquals, hashcode, etc.
         */
    }

public interface IEntity<I extends Serializable> extends Serializable {

    /**
     * Property which represents id.
     */
    String P_ID = "id";

    /**
     * Get primary key.
     *
     * @return primary key
     */
    I getId();

    /**
     * Set primary key.
     *
     * @param id primary key
     */
    void setId(I id);
}

For the above code, my question is, why YourEntityClass need to pass Long in IEntity<Long>? Why not something else like IEntity<String>? Is it because the id is of type Long, and the getter of id must return the same type which we provided to IEntity?

A: 

The YourEntityClass is implementing a generic interface and it is specifying the specific type for gneric interface. It has a method using a specific type (Long) since that is what implementing that interface entails.

+4  A: 

YourEntityClass puts <Long> in IEntity arbitrarily. Any type that implements Serializable can go there.

After you've chosen the type for I, your getId() method has to return that same type.

for example you could have another class that implements IEntity<String> and getId() in that case would have to return a String.

Pablo Fernandez
+1 for giving a second example.
Adeel Ansari
understood very clearly =)
cometta