JPA- insert a ID of parent to child table - jpa

when there is a many to one associate between two object in hibernate(JPA) and we want insert a ID of parent to child table without new record in parent table how do I implement it?
#ManyToOne(targetEntity = RoleEntity.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "FK_ROLE_ID",referencedColumnName = "ID")
private RoleEntity role;
I write this:
UserEntity userEntity=new UserEntity();
userEntity.setUserName(username);
userEntity.setPassword(password);
userEntity.setCreatedDate(new Date().toString());
RoleEntity roleEntity=new RoleEntity();
roleEntity.setTitle("user");
userEntity.setRole(roleEntity);
but the last three line also insert a new record in user table.
This completely of roleEntity:
package Entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by Mohsen on 7/10/2018.
*/
#Entity(name = "role")
#Table(name = "ROLE")
public class RoleEntity implements Serializable {
#Id
#Column(name = "ID")
#SequenceGenerator(name = "SEQ_ROLE", sequenceName = "SEQ_ROLE", allocationSize = 1)
#GeneratedValue(generator = "SEQ_ROLE", strategy = GenerationType.SEQUENCE)
private int id;
#Basic
#Column(name = "Title")
private String title;
// #OneToMany(targetEntity = UserEntity.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
// #JoinColumn(name = "FK_ROLE_ID",referencedColumnName = "ID")
// private Set<UserEntity> user;
public RoleEntity() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
This completely of userEntity:
package Entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Mohsen on 7/10/2018.
*/
#Entity(name = "user")
#Table(name = "USERR")
public class UserEntity implements Serializable {
#Id
#Column(name = "ID")
#SequenceGenerator(name = "SEQ_USER", allocationSize = 1, sequenceName = "SEQ_USER")
#GeneratedValue(generator = "SEQ_USER", strategy = GenerationType.SEQUENCE)
private int id;
#Basic
#Column(name = "UserName", columnDefinition = "VARCHAR2(20 CHAR)")
private String userName;
#Basic
#Column(name = "Password", columnDefinition = "VARCHAR2(255 CHAR)")
private String password;
#Basic
#Column(name = "CreatedDate")
private String createdDate;
#Basic
#Column(name = "EndedDate")
private String endedDate;
#OneToOne(targetEntity = PeopleEntity.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private PeopleEntity people;
#ManyToOne(targetEntity = RoleEntity.class,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
#JoinColumn(name = "FK_ROLE_ID",referencedColumnName = "ID")
private RoleEntity role;
public RoleEntity getRole() {
return role;
}
public void setRole(RoleEntity role) {
this.role = role;
}
public UserEntity() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getEndedDate() {
return endedDate;
}
public void setEndedDate(String endedDate) {
this.endedDate = endedDate;
}
public PeopleEntity getPeople() {
return people;
}
public void setPeople(PeopleEntity people) {
this.people = people;
}
}

I have found the solution
I set cascade = CascadeType.REMOVE in child object and it works

Related

How to load security key from application.properties for #ColumnTransformer...?

package com.srikanth.oncode.entity;
import java.io.Serializable;
import org.hibernate.annotations.ColumnTransformer;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
#Entity
public class Employee implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
#ColumnTransformer(forColumn = "name",
read = "pgp_sym_decrypt(name, 'mykey}')",
write = "pgp_sym_encrypt(?, 'mykey}')")
#Column(name = "name",columnDefinition = "bytea")
String name;
#ColumnTransformer(forColumn = "emailId",
read = "pgp_sym_decrypt(email_id,'mykey}')",
write = "pgp_sym_encrypt(?,'mykey}')")
#Column(name = "emailId",columnDefinition = "bytea")
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Employee(String name, String email) {
super();
this.name = name;
this.email = email;
}
public Employee() {
super();
}
}
```......................................
here i have hardcoded secret key with -> mykey but i want it to be externalized from application.properties.
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
#ColumnTransformer(forColumn = "name",
read = "pgp_sym_decrypt(name, '${mykey}')",
write = "pgp_sym_encrypt(?, '${mykey}')")
#Column(name = "name",columnDefinition = "bytea")
String name;
#ColumnTransformer(forColumn = "emailId",
read = "pgp_sym_decrypt(email_id,'${mykey}')",
write = "pgp_sym_encrypt(?,'${mykey}')")
#Column(name = "emailId",columnDefinition = "bytea")
private String email;
......................
i have tried in this way to load key from application.properties but it not working.

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;
}
}

Merge 3 Tables into 1 SpringBoot + Postgres

I have an Application written in spring boot with 3 Tables T1, T2 and T3 on Postgres
t1 one2many mapping with t2 and t2 one2many with t3
How can I merge these tables into one? Do the model and repository still stay the same?
Model for T1
#Entity
#Table(name = "maintenance_type")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class MaintenanceType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Column(unique=true)
private String changeType;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdAt;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updatedAt;
#OneToMany(mappedBy = "maintenanceType", cascade = CascadeType.ALL)
private Set<TierTwoQuestion> tierTwoQuestion;
public MaintenanceType() {
}
public MaintenanceType(Long id, String changeType) {
super();
this.id = id;
this.changeType = changeType;
}
public MaintenanceType(String changeType) {
super();
this.changeType = changeType;
}
public Set<TierTwoQuestion> getTierTwoQuestion() {
return tierTwoQuestion;
}
//
public void setTierTwoQuestion(Set<TierTwoQuestion> tierTwoQuestion) {
this.tierTwoQuestion = tierTwoQuestion;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getChangeType() {
return changeType;
}
public void setChangeType(String changeType) {
this.changeType = changeType;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
Model for T2
#Entity
#Table(name = "tier_two_question")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class TierTwoQuestion implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Column(unique=true)
private String question;
#ManyToOne
#JoinColumn(name = "maintenanceId", nullable = false)
private MaintenanceType maintenanceType;
#OneToMany(mappedBy = "tierTwoQuestion", cascade = CascadeType.ALL)
private Set<TierThreeQuestion> tierThreeQuestion;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdAt;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updatedAt;
public TierTwoQuestion() {
}
public TierTwoQuestion(Long id) {
super();
this.id = id;
this.question = question;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
// public MaintenanceType getMaintenanceType() {
// return maintenanceType;
// }
public void setMaintenanceType(MaintenanceType maintenanceType) {
this.maintenanceType = maintenanceType;
}
public Set<TierThreeQuestion> getTierThreeQuestion() {
return tierThreeQuestion;
}
public void setTierThreeQuestion(Set<TierThreeQuestion> tierThreeQuestion) {
this.tierThreeQuestion = tierThreeQuestion;
}
}
I tried adding recreating the model with all T1 T2 T3 in one table but not working as expected

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

Add row to join table using JPA

I'm using JPA 2.0 and I'm using a generated schema.
Here is my mapping:
#Entity
#Table(name = "CBV_USER")
public class CbvUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "Login")
private String login;
#Basic(optional = false)
#Column(name = "Password")
private String password;
#Basic(optional = false)
#Column(name = "Email")
private String email;
#Basic(optional = false)
#Column(name = "FirstName")
private String firstName;
#Basic(optional = false)
#Column(name = "LastName")
private String lastName;
#Basic(optional = false)
#Column(name = "Id")
private String id;
#Column(name = "Score")
private BigDecimal score;
#JoinTable(name = "FRIENDSHIP", joinColumns = {
#JoinColumn(name = "Login0", referencedColumnName = "Login")}, inverseJoinColumns = {
#JoinColumn(name = "Login1", referencedColumnName = "Login")})
#ManyToMany
private List<CbvUser> cbvUserList2;
#ManyToMany(mappedBy = "cbvUserList2")
private List<CbvUser> cbvUserList3;
public CbvUser() {
}
public CbvUser(String login) {
this.login = login;
}
public CbvUser(String login, String password, String email, String firstName, String lastName, String id) {
this.login = login;
this.password = password;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BigDecimal getScore() {
return score;
}
public void setScore(BigDecimal score) {
this.score = score;
}
public List<CbvUser> getCbvUserList2() {
return cbvUserList2;
}
public void setCbvUserList2(List<CbvUser> cbvUserList2) {
this.cbvUserList2 = cbvUserList2;
}
public List<CbvUser> getCbvUserList3() {
return cbvUserList3;
}
public void setCbvUserList3(List<CbvUser> cbvUserList3) {
this.cbvUserList3 = cbvUserList3;
}
#Override
public int hashCode() {
int hash = 0;
hash += (login != null ? login.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CbvUser)) {
return false;
}
CbvUser other = (CbvUser) object;
if ((this.login == null && other.login != null) || (this.login != null && !this.login.equals(other.login))) {
return false;
}
return true;
}
#Override
public String toString() {
return "models.CbvUser[login=" + login + "]";
}
}
My problem is that I can't figure out how to add a new row in the Join Table FRIENDSHIP through a specific CbvUser or through an EntityManager.
I'll be really grateful for any help.
Something like this should work:
CbvUser user1 = new CbvUser();
...
CbvUser user2 = new CbvUser();
...
// declare user2 as a friend of user1
List<CbvUser> cbvUserList2 = new ArrayList<CbvUser>();
cbvUserList2.add(user2);
user1.setCbvUserList2(cbvUserList2);
// declare user1 as a friend of user2
List<CbvUser> cbvUserList3 = new ArrayList<CbvUser>();
cbvUserList3.add(user1);
user2.setCbvUserList3(cbvUserList3);
em.persist(user1);
em.persist(user2);
em.flush();
The friendship relation is a (self-referencing) bidirectional association, so you must set both sides of the link correctly (from user1 to user2 and from user2 to user1).
Providing a public add/remove that maintains referential integrity might be even more elegant here.