Do I need to set a childs parent? - jpa

I am having an issue where the Domain (child) is not getting the Business (parents) id. I have the business created and the domain but the domain does not have the business_id. Below is what I was doing originally. I then made a test path that I called which gave the same behavior unless I used the setBusiness method of the domain. Is this the expectation? Do I need to loop over the domains that are passed from a client and set the business?
Test
public void test() {
Business b = new Business();
b.setName("Test Test");
Domain d1 = new Domain();
d1.setName("Domain 1");
d1.setBusiness(b);
em.persist(b);
em.flush();
}
Code
#Entity
#Table(name = "Business")
public class Business {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#OneToMany(mappedBy="business", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Domain> domains = new ArrayList<>();
//...getters and setters
}
-
#Entity
#Table(name = "Domain")
public class Domain {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "business_id", nullable = false)
private Business business;
//...getters and setters
}
I was calling a rest service using the below JSON which then persisted the business.
{
"name": "Business Test ",
"domains": [{"name": "test domain"}]
}
#Path("business")
public class BusinesResouce {
#EJB
BusinessService service;
#Path("create")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void create(Business entity) {
service.persist(entity);
}
//other paths
}
-
#Stateless
public class BusinessService {
private static final String PERSISTENCE_UNIT_NAME = "edc";
#PersistenceContext(unitName = PERSISTENCE_UNIT_NAME)
private EntityManager em;
public void persist(Business entity) {
em.persist(entity);
//Do I really need to loop entity.getDomains and setBusiness?
em.flush();
}
}

Related

How to add new records to a field with #OneToOne in spring Data?

I am making a jsf + spring application.
The database contains a table of games and it is displayed on one of the pages of the site.
Each game has a genre list and development status. These fields are annotated with #OneToMany and #OneToOne respectively and are also tables in the database.
But here's the question: How do I add new games now? How do I initialize these fields? Because the only way I see is to create a new genre for a new game every time. That is, even if game A and games B are of the same genre, then I have to create two different unique genres, not one.
And how to initialize these fields from JSF?
For example from the <p: selectOneMenu> tag
game.java
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "game")
public class Game
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#Column(name = "budget")
private String budget;
#Column(name = "profit")
private String profit;
#Column(name = "number")
private String number;
#OneToOne(optional = false, cascade = CascadeType.REFRESH)
#JoinColumn(name = "platform")
private Platform platform;
#OneToOne(optional = false, cascade = CascadeType.REFRESH)
#JoinColumn(name = "status")
private Status status;
#Column(name = "start")
private Date start;
#Column(name = "end")
private Date end;
#OneToMany(fetch = FetchType.EAGER)
#JoinTable(name = "game_genre",
joinColumns = #JoinColumn(name= "game_id"),
inverseJoinColumns = #JoinColumn(name= "genre_id"))
private List<Genre> listGenre;
public void update(Game new_game)
{
this.name = new_game.name;
this.budget = new_game.budget;
this.profit = new_game.profit;
this.number = new_game.number;
this.platform = new_game.platform;
this.status = new_game.status;
this.start = new_game.start;
this.end = new_game.end;
}
}
development status
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "status")
public class Status implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "Название")
private String Name;
#Column(name = "Описание")
private String description;
public void update(Status new_game)
{
this.description = new_game.description;
this.Name = new_game.Name;
}
}
genre:
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "genre")
public class Genre implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
public void update(Genre new_game)
{
this.name = new_game.name;
this.description = new_game.description;
}
}
Bean
#Component(value = "listgames")
#SessionScope
public class GamesView {
#Autowired
private GamesService gamesService;
private Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
private List<Game> All_games = new ArrayList<Game>();
private Game newGame=new Game();
public Game getNewGame() {
return newGame;
}
public void setNewGame(Game newGame) {
this.newGame = newGame;
}
public void onRowEdit(RowEditEvent event) {
Game new_game=(Game)event.getObject();
All_games.get(new_game.getId()-1).update(new_game);
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "X/Y edit successful!");
FacesContext.getCurrentInstance().addMessage(null, msg);
int i=0;
i++;
}
public void createNew() {
gamesService.addBank(newGame);
newGame = new Game();
}
public List<Game> getAll_games() {
return gamesService.getAll();
}
public void setAll_games(List<Game> all_games) {
All_games = all_games;
}
}

Jpa Auditing dont save data in table auditing

I have to implementes Auditing in my aplication.. i inserting this data correctly
but i want to save all atributter from my Entity ,
Exemple, name, epigrafe, .. and olthers.
I implemented the mothod but dosent work, just dont save the atributte..
lets see..
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "logradouros_historico", schema = "aud")
public class LogradourosHistorico {
#Id
#GeneratedValue
private Long id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_logradouro")
private Logradouros logradouro;
#CreatedBy
private String modificadoPor;
#CreatedDate
#Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate = new Date();
#Enumerated(EnumType.STRING)
private Acoes acao;
#Column(name = "nome")
private String nome; //nome do logradouro
public LogradourosHistorico() {
super();
}
public LogradourosHistorico(Logradouros logradouro, String modificadoPor,
Acoes acao) {
super();
this.logradouro = logradouro;
this.modificadoPor = modificadoPor;
this.acao = acao;
}
//getters and setters
my class entityListner
public class LogradourosEntityListener {
#PostPersist
public void prePersist(Logradouros target) {
perform(target, Acoes.INSERTED);
}
#PreUpdate
public void preUpdate(Logradouros target) {
perform(target, Acoes.UPDATED);
}
#PreRemove
public void preRemove(Logradouros target) {
perform(target, Acoes.DELETED);
}
#Transactional()
private void perform(Logradouros target, Acoes acao) {
target.getNome();
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new LogradourosHistorico(target, acao));
}
}
my class Logradouros
#Entity
#EntityListeners(LogradourosEntityListener.class)
#Table(name = "logradouros", schema = "glb", uniqueConstraints= #UniqueConstraint(columnNames={"id_entidade", "idLogradouro"}))
public class Logradouros extends Auditable<String> implements Serializable {
private static final long serialVersionUID = 3703309412387185484L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idLogradouro;
#Column(name = "cep_geral")
private String cepGeral;
#Column(name = "epigrafe")
private String epigrafe;
#NotNull
#Column(name = "nome")
private String nome;
#Column(name = "nome_exibicao")
private String nomeExibicao;
#JoinColumn(name = "id_entidade")
#ManyToOne(/*cascade = CascadeType.ALL*/)
private Entidades entidade;
#NotNull
#JoinColumn(name = "id_municipio")
#ManyToOne(/*cascade = CascadeType.ALL*/)
private Municipios municipio;
// gettrs and settrs
so what i did wrong because i cant get the nome of entity Logradouros

JPA Entity Mappings between two tables

I keep getting the following error with my Entity mappings.
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: edu.indstate.ics.transcript.web.dao.entity.Swrhxml.swbhxml in edu.indstate.ics.transcript.web.dao.entity.Swbhxml.swrhxmls
I am not sure what I am doing wrong. Could use some insight and help on what I am missing here.
My Entity classes are as follows:
#Entity
#Table(name = "SWBHXML" )
public class Swbhxml implements DatabaseObject, Serializable {
private List<Swrhxml> swrhxmls;
private static final long serialVersionUID = 1L;
private Long swbhxmlTransId;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SWBHXML_TRANS_ID", nullable = false)
public Long getSwbhxmlTransId() {
return swbhxmlTransId;
}
public void setSwbhxmlTransId(Long swbhxmlTransId) {
this.swbhxmlTransId = swbhxmlTransId;
}
#OneToMany(mappedBy = "swbhxml", cascade = CascadeType.ALL)
public List<Swrhxml> getSwrhxmls() {
return swrhxmls;
}
public void setSwrhxmls(List<Swrhxml> swrhxmls) {
this.swrhxmls = swrhxmls;
}
}
#Entity
#Table(name = "SWRHXML" )
public class Swrhxml implements DatabaseObject, Serializable {
private Swbhxml swbhxml;
private static final long serialVersionUID = 1L;
private Long SwrhxmlTransId;
private String SwrhxmlHxpsCode;
private Date SwrhxmlTimeStamp;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="SWBHXML_TRANS_ID")
public Swbhxml getSwrhxml() {
return swbhxml;
}
public void setSwrhxml(Swbhxml swbhxml) {
this.swbhxml = swbhxml;
}
#Column(name = "SWRHXML_HXPS_CODE", length = 15)
public String getSwrhxmlHxpsCode() {
return SwrhxmlHxpsCode;
}
public void setSwrhxmlHxpsCode(String SwrhxmlHxpsCode) {
this.SwrhxmlHxpsCode = SwrhxmlHxpsCode;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SWRHXML_TIMESTAMP", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
public Date getSwrhxmlTimeStamp() {
return SwrhxmlTimeStamp;
}
public void setSwrhxmlTimeStamp(Date SwrhxmlTimeStamp) {
this.SwrhxmlTimeStamp = SwrhxmlTimeStamp;
}
}
You use
`mappedBy = "swbhxml"`
^
|___ b here
, but the annotated association is
Swbhxml getSwrhxml()
^
|___ r here
Your getter and setter are named incorrectly. And frankly, with such cryptic and close entity names, you'll probably have many such bugs.

Spring Data with Integration Test OneToMany ManyToOne

I know that this topic is not new, but I few days try to solve task.
I have 3 classes - Client, Account and Invoice.
Client has many Accoutns, Account has many Invoices.
I mapped them:
Client
#Entity
#Table(name = "CLIENT")
public final class Client implements Serializable {
...
#Column(length = 36, nullable = false, unique = true, updatable = false)
private String uuid;
#OneToMany(mappedBy = "client", cascade = CascadeType.ALL)
private List<Account> accounts;
...
}
Account
#Entity
#Table(name = "ACCOUNT")
public final class Account implements Serializable {
...
#ManyToOne
#JoinColumn(name = "client_uuid", referencedColumnName = "uuid", nullable = false)
private Client client;
#OneToMany(mappedBy = "account", cascade = CascadeType.ALL)
private List<Invoice> invoices;
...
}
Invoice
#Entity
#Table(name = "INVOICE")
public final class Invoice implements Serializable {
#ManyToOne
#JoinColumn(name = "account_uuid", referencedColumnName = "uuid", nullable = false)
private Account account;
}
I use Spring Data Jpa:
#Repository
public interface SpringDataClientRepository extends ClientRepository, JpaRepository<Client, Integer> {
Others the same.
When I try to run ITests, test with client work fine:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { JpaConfig.class, ITDaoConfig.class })
public class ITClientRepository {
private static final Logger log = Logger.getLogger(ITClientRepository.class);
#Autowired
private ClientRepository clientRepository;
#Test
#Transactional
public void testSaveClient() {
log.info("testSaveClient start");
Client client = new Client();
client.setName("testSaveClient");
client.setUuid("client-testSaveClient");
client.setTelephone("12345679");
Account account = new Account();
account.setClient(client);
account.setMoneyCount(10);
account.setUuid("client-testSaveClient");
client.addAccount(account);
log.info(client.toString());
Client getClient = clientRepository.save(client);
log.info(client.toString());
It saves client and account in. But this test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { JpaConfig.class, ITDaoConfig.class })
public class ITAccountRepository {
private static final Logger log = Logger.getLogger(ITAccountRepository.class);
#Autowired
private AccountRepository accountRepository;
#Test
#Transactional
public void testSaveAccount() {
log.info("testSaveAccount start");
Client client = new Client();
client.setName("testSaveAccount");
client.setTelephone("12345679");
client.setUuid("account-testSaveAccount");
client.setId(200);
// Client saved in db
Account account = new Account();
account.setClient(client);
account.setMoneyCount(15);
account.setUuid("account-testSaveAccount");
client.addAccount(account);
Invoice invoice = new Invoice();
invoice.setAccount(account);
invoice.setAmount(11);
Date date = new Date();
invoice.setCreated(date);
invoice.setUuid("account-testSaveClient");
invoice.setDescription("Description of invoice");
account.addInvoice(invoice);
log.info(account.toString());
Account getAccount = accountRepository.save(account);
log.info(account.toString());
fail with:
Caused by: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : projects.model.Invoice.account -> projects.model.Account
I want that all Invoices will be saved if I save Account of those invoices. And the same with Client - all Accounts will be saved if I save Client of them. How I do this?
I made a change to have a unidirectional relationship with composition:
Client
#Entity
#Table(name = "CLIENT")
public final class Client extends BaseEntity {
#Column(length = 36)
private String uuid;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
#JoinColumn(name = "client_id", referencedColumnName = "id")
private List<Account> accounts;
}
Invoice
#Entity
#Table(name = "INVOICE")
public final class Invoice extends BaseEntity {
#Column(length = 36)
private String uuid;
}
Account
#Entity
#Table(name = "ACCOUNT")
public final class Account extends BaseEntity {
#Column(length = 36)
private String uuid;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
#JoinColumn(name = "account_id", referencedColumnName = "id")
private List<Invoice> invoices;
}
In the test, I left everything like it was. And it all works now.

Seeing "referencedColumnNames(ID) ... not mapped to a single property" error with a 1-M relationship after adding a composite key to the "1" side

I have an existing JPA entity ("Reference") with an ID column as its primary key that it inherits from a base class "BaseEntity" (using the #MappedSuperclass annotation on the superclass).
I also have a 1-M relationship between a Reference and another entity called Violation. Violation was previously defined with a foreign key "REFERENCE_ID" to the "ID" column of the Reference entity.
Recently, I tried to add an unrelated composite key to the Reference entity. This should not have affected the 1-M relationship between Reference and Violation. However, when I run the code in my tomcat server, I see the following stack trace:
Caused by: org.hibernate.AnnotationException: referencedColumnNames(ID) of org.qcri.copydetection.sdk.metastore.entity.Violation.reference referencing org.qcri.copydetection.sdk.metastore.entity.Reference not mapped to a single property
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:205) ~[hibernate-annotations-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:110) ~[hibernate-annotations-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.cfg.AnnotationConfiguration.processEndOfQueue(AnnotationConfiguration.java:541) ~[hibernate-annotations-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:523) ~[hibernate-annotations-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:380) ~[hibernate-annotations-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1206) ~[hibernate-core-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1459) ~[hibernate-entitymanager-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:193) ~[hibernate-entitymanager-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1086) ~[hibernate-entitymanager-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:685) ~[hibernate-entitymanager-3.5.6-Final.jar:3.5.6-Final]
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73) ~[hibernate-entitymanager-3.5.6-Final.jar:3.5.6-Final]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268) ~[spring-orm-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310) ~[spring-orm-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) ~[spring-beans-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ~[spring-beans-3.1.2.RELEASE.jar:3.1.2.RELEASE]
... 39 common frames omitted
Here is the code for the 3 classes involved:
#Entity
#Table(name = "REFERENCE")
#XmlRootElement
#XmlAccessorType(XmlAccessType.PROPERTY)
#IdClass(Reference.ContextualName.class)
public class Reference extends BaseEntity {
#Column(name= "LOCATION", unique=true)
#XmlElement
private String location;
#Id
#AttributeOverrides({
#AttributeOverride(name = "name", column = #Column(name = "NAME")),
#AttributeOverride(name = "account", column = #Column(name = "ACCOUNT_ID"))
})
#Column(name = "NAME")
#XmlElement
private String name;
#ManyToOne(optional=false)
#XmlTransient
#JoinColumn(name = "ACCOUNT_ID", referencedColumnName = "ID")
private Account account;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Reference() {}
public Reference(String name) {
setName(name);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public Account getAccount() {
return this.account;
}
public void setAccount(Account account) {
this.account = account;
}
#Embeddable
private class ContextualName implements Serializable {
private static final long serialVersionUID = -3687389984589209378L;
#Basic(optional = false)
#Column(name = "NAME")
#XmlElement
private String name;
#ManyToOne(optional=false)
#XmlTransient
#JoinColumn(name = "ACCOUNT_ID", referencedColumnName = "ID")
private Account account;
ContextualName() {}
}
}
#MappedSuperclass
#XmlAccessorType(XmlAccessType.FIELD)
public abstract class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
#XmlElement
private Long id;
#Basic(optional = true)
#Column(name = "CREATED", insertable = false, updatable = false, columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
#Temporal(TemporalType.TIMESTAMP)
#XmlElement
private Date creationDate;
protected BaseEntity() {}
public Long getId() {
return id;
}
public void setId(Long id) {
if(this.id==null) {
this.id = id;
} else if (this.id!=id) {
throw new IllegalArgumentException("Cannot change the id after it has been set, as it is a generated field.");
}
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
if(this.creationDate==null) {
this.creationDate = creationDate;
} else if (this.creationDate!=creationDate) {
throw new IllegalArgumentException("Cannot change the creation-date after it has been set, as it is a generated field.");
}
}
}
#Entity
#Table(name = "VIOLATION")
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Violation extends BaseEntity {
#ManyToOne (optional=false, fetch= FetchType.EAGER)
#JoinColumn(name = "REFERENCE_ID", referencedColumnName = "ID")
private Reference reference;
#ManyToOne (optional=false, fetch= FetchType.EAGER)
#JoinColumn(name = "SUSPECT_ID", referencedColumnName = "ID")
private Suspect suspect;
#ManyToOne (optional=false, fetch= FetchType.EAGER)
#XmlTransient
#JoinColumn(name = "SEARCH_ID", referencedColumnName = "ID")
private Search search;
#Basic(optional = false)
#Column(name = "SCORE")
#XmlElement
private double score;
public Violation() {}
public Violation(Search search, Reference ref, Suspect sus, double score) {
this.search = search;
this.reference = ref;
this.suspect = sus;
this.score = score;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Reference getReference() {
return reference;
}
public void setReference(Reference reference) {
this.reference = reference;
}
public Suspect getSuspect() {
return suspect;
}
public void setSuspect(Suspect suspect) {
this.suspect = suspect;
}
public Search getSearch() {
return search;
}
public void setSearch(Search search) {
if(this.search!=null && this.search!=search) {
this.search.removeViolation(this);
}
this.search = search;
if(search!=null) {
if(!search.getViolations().contains(this)) {
search.addViolation(this);
}
}
}
}
To cut a long story short, I'm totally confused how to go about adding a composite key to an existing (legacy) entity that already has an ID column. I can't remove the ID column, nor can I change the 1-M relationship between Reference and Violation. I can't for the life of me understand the error message because the "REFERENCE_ID" foreign key column of the Violation entity is being mapped to a single "ID" column of the Reference entity.
Many thanks in advance!