How can one override a method from a Hibernate @MappedSuperclass but keep the originial mapping?

狂风中的少年 提交于 2019-12-13 04:03:21

问题


I have a mapped super class that I use to define a method it's persistence mapping. I am using the table-per-class inheritance strategy. For example here is some simple class inheritance:

@MappedSuperclass
public class Feline {
    private Long id;
    private String identifier;

    @GeneratedValue(strategy = "GenerationType.AUTO")
    @Id
    public Long getId() {
        return id;
    }

    public String getIdentifier() {
        return identifier;
    }
    // other getters and setters, methods, etc.
}

The next class does not override the getIdentifier() method and saves the Cat's identifier in the "identifier" column of it's entity table.

@Entity
public class Cat extends Feline {
    private Date dateOfBirth;
    private Set<Kitten> kittens;

    @OneToMany(mappedBy = "mother")
    public Set<Kitten> getKittens() {
        return kittens;
    }
    // other getters and setters, methods, etc.
}

In the Kitten class I want to change the identifier to return the Kitten.identifier + " kitten of " + mohter.getIdentifier() or for example "Boots kitten of Ada" and persist this String in the "identifier" column of the entity's table.

@Entity
public class Kitten extends Cat {
   private Cat mother;

   @ManyToOne
   public Cat getMother() {
       return mother;
   }

   @Override
   public String getIdentifier() {
       return this.getIdentifier() + " kitten of " + mother.getIdentifier(); 
   }
}

When I run this code I get an error message "Caused by: org.Hibernate.MappingException: Duplicate property mapping of identifier found in com.example.Kitten."

Since I am extending a @Mappedsuperclass the identifier field should be mapped to the "identifier" column of each entity table but for some reason this doesn't happen and it tries to map the identifier field twice when I override the getIdentifier() method in the Kitten class.

Both the Cat and Kitten tables have "identifier" columns. I do not understand why I cannot override a method if it returns the correct type to map to the same column.


回答1:


That won't work. But you can define a discriminator.

Have a look at http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/inheritance.html



来源:https://stackoverflow.com/questions/21561696/how-can-one-override-a-method-from-a-hibernate-mappedsuperclass-but-keep-the-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!