Extending a table in Hibernate which has some relations - java

I have an Entity that would like to extend it by adding some fields. first of all they are not accessible to me to change directly, they are in their own jar file. here are the base entities:
#Entity
table(name="ACCOUNTDEF")
public class EtAccountDef
{
private String cNumber;
private List<EtAccount> accounts = new ArrayList();
public String getCNumber()
{
return cNumber;
}
public void setCNumber(String cNumber) {
this.cNumber = cNumber;
}
#OneToMany(fetch=FetchType.LAZY, cascade={javax.persistence.CascadeType.ALL}, mappedBy="accountDef")
public List<EtAccount> getAccounts() {
return accounts;
}
public void setAccounts(List<EtAccount> accounts) {
this.accounts = accounts;
}
}
which is the parent class and the below is child class:
#Entity
#Table(name="ACCOUNT")
public class EtAccount
{
private Double accountAmount;
private EtAccountDef accountDef;
private List<EtAccountItems> accountItems = new ArrayList();
#ManyToOne(fetch=FetchType.LAZY)
public EtAccountDef getAccountDef() {
return accountDef;
}
public void setAccountDef(EtAccountDef accountDef) {
this.accountDef = accountDef;
}
#OneToMany(fetch=FetchType.LAZY, cascade={javax.persistence.CascadeType.ALL}, mappedBy="account")
public List<EtAccountItems> getAccountItems() {
return accountItems;
}
public void setAccountItems(List<EtAccountItems> accountItems) {
this.accountItems = accountItems;
}
}
so I tried these changes to achieve my goal.
#MappedSuperclass
public abstract class OtAbstractAccount extends EtAccount {
private Double AccountCommission;
#Column(columnDefinition="decimal(15,2)")
public Double getAccountCommission() {
return accountCommission;
}
public void setAccountCommission(Double accountCommission) {
this.accountCommission = accountCommission;
}
and then extend it by this entity:
#Entity
#Table(name="ACCOUNT")
public class OtCostumAccount extends OtAbstractAccount {
}
The fields are now added to the base table(EtAccount) but
after compiling I get an error in the Weblogic that says:
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne
on EtAccount.accountDef references an unknown entity: EtAccountDef
I have entered these two line in my ORM file:
<mapped-superclass class="package.OtAbstractAccount" />
<entity class="package.OtCostumAccount" />
Surprisingly when i comment
<mapped-superclass class="package.OtAbstractAccount" />
from ORM the weblogic does not rise any error but when I try to load object another error will be created that say:
Caused by: javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: ORA-00904:
"OtCostumAccount "."DTYPE": invalid identifier
I'm confused whit these error and I'll appreciate any help.

If you can not modify the parent class, then the default hibernate inheritance strategy apply: one table per class. This strategy require a discriminant column which, by default, is DTYPE. Did you try to add a discriminator column to your OtCostumAccount entity or create the DTYPE column ?

Related

Basic attribute should not be - with my own type

I have a problem with the hibernate entity, and I would like to know if it is something I overlooked or if it is a bug in IntelliJ IDEA.
I have a Value object bank account:
class BankAccount
{
private String value;
public BankAccount(String value) {
// validation
this.value;
}
}
Which has defined it's own hibernate type:
public class BankAccountType extends AbstractSingleColumnStandardBasicType<BankAccount> {
public static final BankAccountType INSTANCE = new BankAccountType();
public static final String NAME = "bankAccount";
public BankAccountType() {
super(LongVarcharTypeDescriptor.INSTANCE, BankAccountTypeDescriptor.INSTANCE);
}
#Override
public String getName() {
return null;
}
}
And I have an entity:
#Entity
#TypeDefs({
#TypeDef(
name = BankAccountType.NAME,
typeClass = BankAccountType.class,
defaultForType = BankAccount.class
)
})
class User {
private UUID id;
//...
#Column
private BankAccount bankAccount;
//...
}
It works perfectly, but IDEA keeps telling me 'Basic attribute should not be BankAccount.'
Is there any way, how to get rid of this error without changing my entities? Is it a good idea to use value objects as a column in my entities?
Thanks a lot!

Spring Runtime Error,No identifier specified for entity:

New to java and spring. Tried creating an app but was unsuccessful.I have the following entity and controller in my app. But at runtime i get an error. I posted snippets for easier reading.
staff.java
#Data
#Entity
public class Staff {
private int staff_id;
private String staff_name;
private String staff_email;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "staff")
private List<VisitRequest> visitRequest;
public String getStaff_name(){
return staff_name;
}
public void setStaff_name(String staff_name){
this.staff_name = staff_name;
}
public String getStaff_email(){
return staff_email;
}
public void setStaff_email(String staff_email){
this.staff_email = staff_email;
}
public int getStaff_id(){
return staff_id;
}
public void setStaff_id(int staff_id){
this.staff_id = staff_id;
}
}
StaffController.java
#Controller
#RestController
#RequestMapping("/staff/")
public class StaffController{
#Autowired
protected StaffRepository staffRepository;
#GetMapping("/Staff")
public List<Staff> getAllStaff() {
return staffRepository.findAll();
}
#GetMapping("/staff/{Staff_id}")
public ResponseEntity<Staff> getStaffById(#PathVariable(value = "Staff_id") Long Staff_id)
throws ResourceNotFoundException{
Staff staff = staffRepository.findById(Staff_id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not Found"));
return ResponseEntity.ok().body(staff);
And the error that is thrown at runtime is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfigura
tion.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.Vportal.data.model.Staff
Please advice on what to do.
Your Staff entity lacks a member with an #Id annotation. This could be added to staff_id like follows:
#Data
#Entity
public class Staff {
#Id
private int staff_id;
....
}

Spring Data - no property found

I have Entity
#Entity
#Table(name = "messages")
public class Message {
...
#Column(name = "isVisibleForSender")
private boolean isVisibleForSender;
}
and Spring Data repository
#Repository
#Transactional
public interface MessageCRUDRepository extends JpaRepository<Message, Long> {
...
public boolean getVisibleForRecipient(boolean isVisibleForRecipient);
}
When compiling, the program throws me an exception Caused by: org.springframework.data.mapping.PropertyReferenceException: No property getIsVisibleForRecipient found for type Message!
After seeing your comments, you have the wrong method name:
#Entity
#Table(name = "messages")
public class Message {
#Column(name = "isVisibleForRecipient")
private boolean visibleForRecipient;
}
And for the repo:
interface MessageCRUDRepository extends JpaRepository<Message, Long> {
List<Message> findByVisibleForRecipient(Boolean bool);
}
Make sure you have getters and setters for the visibleForRecipient field in the message object

JPA Entity by extending a MappedSuperclass POJO

I have the following class
#MappedSuperclass
public class Keyword {
private Integer code;
private Integer rating;
public Keyword() {}
public Integer getCode() {
return this.code;
}
public Integer getRating() {
return this.rating;
}
public void setCode(Integer code) {
this.code = code;
}
public void setRating(Integer rating) {
this.rating = rating;
}
}
I want to create an Entity by extending this class and I want to set an already existing field as the primary key (I don't want to create new fields), so I tried to do something like this:
#Entity
#Table(name = "keyword")
//#AttributeOverride(name = "code", column = #Column(name = "code"))
public class MyKeyword extends Keyword {
#Override
#Id
#GeneratedValue
public Integer getCode() {
return super.getCode();
}
}
This gives me the following error when ran
Caused by: org.hibernate.MappingException: Repeated column in mapping
for entity: com.foo.model.MyKeyword column: code (should be mapped
with insert="false" update="false")
Any idea how can I properly configure this up? Keep in mind I have no access to the MappedSuperclass, I can't modify it whatsoever.

Spring BeanUtils couldn't instantiate generic class

I am trying to implement something for converting between my Entities and DTO.
I have base class for my DTOs (called Models):
public class BaseModel<Entity> implements Model<Entity> {
#Override
public Entity toEntity(Class<Entity> entityClass) {
Entity entityInstance = BeanUtils.instantiate(entityClass);
BeanUtils.copyProperties(this, entityInstance);
return entityInstance;
}
}
But following test doesn't passes:
public class BaseModelTest {
#Entity
public class SomeEntity {
#Id
private Long id;
private String name;
public SomeEntity() {
}
public SomeEntity(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
#Test
public void toEntity_givenEntityClass_shouldCreateNewInstance() throws Exception {
//given
BaseModel<SomeEntity> model = new BaseModel();
//when
SomeEntity entity = model.toEntity(SomeEntity.class);
//then
assertNotNull(entity);
}
}
I got exception: (despite the fact, under debugger I see all ctors):
org.springframework.beans.BeanInstantiationException: Failed to instantiate [package.BaseModelTest$SomeEntity]: Is it an abstract class?; nested exception is java.lang.InstantiationException: package.BaseModelTest$SomeEntity
Caused by: java.lang.InstantiationException: package.BaseModelTest$SomeEntity
Caused by: java.lang.NoSuchMethodException: package.BaseModelTest$SomeEntity.<init>()
Currently to create a new SomeEntity instance you need an instance of the enclosing BaseModelTest class. SomeEntity should be an inner static class. Replace:
public class SomeEntity {
with
public static class SomeEntity {
BTW. There is no point in having a DTO class if it maps 1-1 to a model class, it does not add any value, it is only boilerplate code.

Categories

Resources