The name of the variable is added to the name of the column - postgresql

I have two entities - Group and UserGroup, they are connected with groupId.
"\" are because postgre is case sensitive and this way we correct this fact.
#Entity
#Table(name = "\"Group\"")
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "\"groupId\"")
private int groupId;
#Column(name = "\"groupName\"")
private String groupName;
#OneToMany(mappedBy = "group")
List<Project> projects;
#OneToMany(mappedBy = "group")
private List<UserGroup> members;
public Group(String groupName) {
this.groupName = groupName;
}
public Group() {
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public List<UserGroup> getMembers() {
return members;
}
public void setMembers(List<UserGroup> members) {
this.members = members;
}
#Override
public String toString() {
return "Group{" +
"groupId=" + groupId +
", groupName='" + groupName + '\'' +
'}';
}
}
And UserGroup
#Entity
#Table(name = "\"UserGroup\"")
#IdClass(GroupAssociationId.class)
public class UserGroup {
#Id
#Column(name = "\"userId\"")
private int userId;
#Id
#Column(name = "\"groupId\"")
private int groupId;
#ManyToOne
#PrimaryKeyJoinColumn(name = "\"userId\"", referencedColumnName = "\"userId\"")
private User member;
#ManyToOne
#PrimaryKeyJoinColumn(name = "\"groupId\"", referencedColumnName = "\"groupId\"")
private Group group;
#ManyToOne
#JoinColumn(name = "\"accessId\"")
private Access access;
public UserGroup(Group group, User member, Access access) {
this.group = group;
this.member = member;
this.access = access;
}
public UserGroup() {
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public User getMember() {
return member;
}
public void setMember(User member) {
this.member = member;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public Access getAccess() {
return access;
}
public void setAccess(Access access) {
this.access = access;
}
#Override
public String toString() {
return "UserGroup{" +
"userId=" + userId +
", groupId=" + groupId +
", access=" + access.getAccessName() +
'}';
}
}
When I try to create a row in a table UserGroup I get a mistake:
Caused by: org.postgresql.util.PSQLException: ERROR: column "group_groupId" of relation "UserGroup" does not exist
Why? This happens on the string "em.getTransaction().commit(). It is really strange.

In the table UserGroup, a column:
"group_`groupId`"
was generated (because you are using "" to preserve case sensitive.
You can edit in postgres the name for the column (and the foreing key too):
"group_`groupId`" ---> "group_groupId"
JPA is looking for group_groupId.

I've managed to answer this question. The problem was in sequence generation. When generating in embedded database, I don't know why, the generation type sequence doesn't work. Instead I used Identity type and everything started working

Related

Spring Data JPA. Parent table data is not getting rolled back when exception occurred while inserting record in child table

I have 2 tables one to many relationship between Employee and Department table, Employee table are having column Id as PK, Name and Sal whereas Department table having column Dept_ID,Dept_Name & Dept_Loc and primary key is (Dept_ID,Dept_Name) i.e composite key and Dept_ID is foreign key ref from Employee table's Id column. The issue is when I save record in parent table i.e Employee it get saved but if in case I get exception while inserting record for child table i.e Department table,,data is not getting rolled back for EMployee table. Please help I m struggling and I am attaching my code.
public class GlEmployee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "emp_seq")
#Column(name = "EMP_ID")
private long empId;
#Column(name = "EMP_CITY")
private String empCity;
#Column(name = "EMP_NAME")
private String empName;
#Column(name = "EMP_SALARY")
private BigDecimal empSalary;
// bi-directional many-to-one association to EmpDepartment
#OneToMany(mappedBy = "glEmployee",cascade = CascadeType.ALL)
private List<EmpDepartment> empDepartments = new ArrayList<>();
public GlEmployee() {
}
public long getEmpId() {
return this.empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
public String getEmpCity() {
return this.empCity;
}
public void setEmpCity(String empCity) {
this.empCity = empCity;
}
public String getEmpName() {
return this.empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public BigDecimal getEmpSalary() {
return this.empSalary;
}
public void setEmpSalary(BigDecimal empSalary) {
this.empSalary = empSalary;
}
public List<EmpDepartment> getEmpDepartments() {
return this.empDepartments;
}
public void setEmpDepartments(List<EmpDepartment> empDepartments) {
this.empDepartments = empDepartments;
}
public EmpDepartment addEmpDepartment(EmpDepartment empDepartment) {
getEmpDepartments().add(empDepartment);
empDepartment.setGlEmployee(this);
return empDepartment;
}
public EmpDepartment removeEmpDepartment(EmpDepartment empDepartment) {
getEmpDepartments().remove(empDepartment);
empDepartment.setGlEmployee(null);
return empDepartment;
}
}
#Entity
#Table(name = "EMP_DEPARTMENT")
public class EmpDepartment implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private EmpDepartmentPK id;
#Column(name = "DEP_LOC")
private String depLoc;
public EmpDepartment(EmpDepartment id, String dep) {
}
// bi-directional many-to-one association to GlEmployee
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "DEP_ID", insertable = false, updatable = false)
private GlEmployee glEmployee;
public EmpDepartment() {
}
public EmpDepartmentPK getId() {
return this.id;
}
public void setId(GlEmployee glEmployee, String deptName) {
EmpDepartmentPK empDepartment = new
EmpDepartmentPK(glEmployee.getEmpId(), deptName);
this.id = empDepartment;
}
public String getDepLoc() {
return this.depLoc;
}
public void setDepLoc(String depLoc) {
this.depLoc = depLoc;
}
public GlEmployee getGlEmployee() {
return this.glEmployee;
}
public void setGlEmployee(GlEmployee glEmployee) {
this.glEmployee = glEmployee;
}
}
#Embeddable
public class EmpDepartmentPK implements Serializable {
// default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name = "DEP_ID")
private long depId;
#Column(name = "DEP_NAME")
private String depName;
public EmpDepartmentPK() {
}
public EmpDepartmentPK(long depId, String depName) {
super();
this.depId = depId;
this.depName = depName;
}
public long getDepId() {
return this.depId;
}
public void setDepId(long depId) {
this.depId = depId;
}
public String getDepName() {
return this.depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository employeeRepository;
#Transactional
public void createEmp() {
GlEmployee employee = new GlEmployee();
employee.setEmpCity("Pune");
employee.setEmpName("Ankush");
employee.setEmpSalary(new BigDecimal(200));
employeeRepository.save(employee);
EmpDepartment department = new EmpDepartment();
department.setId(employee, "ME");
department.setDepLoc(null);
department.setGlEmployee(employee);
employee.addEmpDepartment(department);
employeeRepository.save(employee);
}
}

Spring boot CrudRepository save - exception is org.hibernate.type.SerializationException: could not serialize

Not sure why I have an issue here, but when I save with a CrudRepository with these objects, I get the SerializationException (with no further information). Can someone take a look at my objects and offer me some insight into why they can't serialize? My pom.xml is attached last as well in case that helps somehow. I'm using a Postgres database.
EDIT: The database and now - tables are created, but objects are not creating rows.
The actual CrudRepository interface:
public interface AccountRepository extends CrudRepository<ZanyDishAccount, String> {}
ZanyDishAccount entity:
#Entity
public class ZanyDishAccount {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id; // internal id of the customer account for a Zany Dish subscription
private String status;
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "company_id")
private Company company;
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "order_id")
private Order order;
public ZanyDishAccount() {}
public ZanyDishAccount(Company company, Order order) {
this.company = company;
this.order = order;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+ ", company = " + company + ", status = " + status + "]";
}
}
Company entity:
#Entity
public class Company {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id;
private String phoneNumber;
private String website;
private String name;
private String uuid;
private String country;
public Company() {}
public Company(String phoneNumber, String website, String name, String uuid, String country) {
this.phoneNumber = phoneNumber;
this.website = website;
this.uuid = uuid;
this.country = country;
}
public String getPhoneNumber ()
{
return phoneNumber;
}
public void setPhoneNumber (String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public String getWebsite ()
{
return website;
}
public void setWebsite (String website)
{
this.website = website;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getUuid ()
{
return uuid;
}
public void setUuid (String uuid)
{
this.uuid = uuid;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
#Override
public String toString()
{
return "ClassPojo [phoneNumber = "+phoneNumber+", website = "+website+", name = "+name+", uuid = "+uuid+", country = "+country+"]";
}
}
Order entity:
#Entity
#Table(name = "_order")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id;
private String pricingDuration;
private Items[] items;
private String editionCode;
public Order() {}
public Order(String pricingDuration, Items[] items, String editionCode) {
this.pricingDuration = pricingDuration;
this.items = items;
this.editionCode = editionCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPricingDuration ()
{
return pricingDuration;
}
public void setPricingDuration (String pricingDuration)
{
this.pricingDuration = pricingDuration;
}
public Items[] getItems ()
{
return items;
}
public void setItems (Items[] items)
{
this.items = items;
}
public String getEditionCode ()
{
return editionCode;
}
public void setEditionCode (String editionCode)
{
this.editionCode = editionCode;
}
#Override
public String toString()
{
return "ClassPojo [pricingDuration = "+pricingDuration+", items = "+items+", editionCode = "+editionCode+"]";
}
}
Thanks for your help!
Mike
Hm, this seems multi-faceted. Let's see if I can help at all. Last thing first...
No tables being created automatically.
I would take a look at this section in Spring's docs for the most basic approach: Initialize a database using Hibernate. For example, spring.jpa.hibernate.ddl-auto: create-drop will drop and re-create tables each time the application runs. Simple and easy for initial dev work. More robust would be leveraging something like Flyway or Liquibase.
Serialization issue
So without logs, and the fact that you have no tables created, the lack of a persistence layer would be the assumed culprit. That said, when you have tables and data, if you do not have a repository for all of the related tables, you'll end up with a StackOverflow error (the serialization becomes circular). For that, you can use #JsonBackReference (child) and #JsonManagedReference (parent). I have been successful using only #JsonBackReference for the child.
Items[]
I'm not sure what Item.class looks like, but that looks like an offensive configuration that I missed the first round.
Change private Items[] items; to private List<Item> items = new ArrayList<Item>();. Annotate with #ElementCollection.
Annotate Item.class with #Embeddable.

Persisting a Joint Table in JPA

I have three entities, Trader, Portfolio and Member. Each Trader has a Portfolio and a Portfolio can have many Members. I have set up the following relationships. I'm not sure how to use the Jointable that is created, i.e. Portfolio_PORTFOLIOID and members_MEMBERID. Obviously I'd like to associate each portfolid with member id's, however I'm not sure how to go about this. How is the jointable data persisted?
My Portfolio class
#Entity
#Table(name="Portfolio")
#NamedQuery(
name="findPortfolioByTrader",
query="SELECT p FROM Portfolio p" +
" WHERE Trader = :trader"
)
public class Portfolio {
#Id
#GeneratedValue
private Integer portfolioId;
#Temporal(TIMESTAMP)
private Date lastUpdate;
private Integer balance;
private Trader trader;
private Collection<Member> members;
public Portfolio() {
this.lastUpdate = new Date();
}
public Portfolio(Integer balance, Trader trader) {
this.lastUpdate = new Date();
this.balance = balance;
this.trader = trader;
}
public Integer getPortfolioId() {
return portfolioId;
}
public void setPortfolioId(Integer portfolioId) {
this.portfolioId = portfolioId;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
#ManyToMany
#JoinTable(
name="MEMBER_PORTFOLIO",
joinColumns=
#JoinColumn(name="Member_MEMBERID", referencedColumnName="MEMBERID"),
inverseJoinColumns=
#JoinColumn(name="portfolio_PORTFOLIOID", referencedColumnName="PORTFOLIOID")
)
public Collection<Member> getMembers() {
return members;
}
public void setMembers(Collection<Member> members) {
this.members = members;
}
#OneToOne(cascade=ALL, mappedBy="portfolio")
public Trader getTrader()
{
return trader;
}
public void setTrader(Trader trader)
{
this.trader = trader;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
}
My Member class
#Entity
#Table(name="Member")
#NamedQuery(
name="findAllMembers",
query="SELECT m FROM Member m " +
"ORDER BY m.memberId"
)
public class Member implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -468520665316481235L;
private String memberId;
private String forename;
private String surname;
private Integer position;
private Integer majority;
private Integer IPO;
private Integer questions;
private Integer answers;
private Party party;
private Date lastUpdate;
private char status;
private Collection<Portfolio> portfolios;
private Collection<AskOrder> askOrders;
private Collection<BidOrder> bidOrders;
public Member() {
this.lastUpdate = new Date();
}
public Member(String memberId,String forename, String surname, Integer position,
Integer majority, Integer IPO, Integer questions, Integer answers, Party party) {
this.memberId = memberId;
this.forename = forename;
this.surname = surname;
this.position = position;
this.majority = majority;
this.IPO = IPO;
this.questions = questions;
this.answers = answers;
this.party = party;
this.lastUpdate = new Date();
this.askOrders = new ArrayList<AskOrder>();
this.bidOrders = new ArrayList<BidOrder>();
this.portfolios = new ArrayList<Portfolio>();
}
#Id
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public char getStatus() {
return status;
}
public void setStatus(char status) {
this.status = status;
}
#Temporal(TIMESTAMP)
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public String getForename()
{
return forename;
}
public void setForename(String forename)
{
this.forename = forename;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public Integer getMajority() {
return majority;
}
public void setMajority(Integer majority) {
this.majority = majority;
}
public Integer getIPO() {
return IPO;
}
public void setIPO(Integer iPO) {
IPO = iPO;
}
public Integer getQuestions() {
return questions;
}
public void setQuestions(Integer questions) {
this.questions = questions;
}
public Integer getAnswers() {
return answers;
}
public void setAnswers(Integer answers) {
this.answers = answers;
}
#ManyToOne
public Party getParty() {
return party;
}
public void setParty(Party party) {
this.party = party;
}
#OneToMany(cascade=ALL, mappedBy="member")
public Collection<AskOrder> getAskOrders()
{
return askOrders;
}
public void setAskOrders(Collection<AskOrder> orders)
{
this.askOrders = orders;
}
#OneToMany(cascade=ALL, mappedBy="member")
public Collection<BidOrder> getBidOrders()
{
return bidOrders;
}
public void setBidOrders(Collection<BidOrder> bidOrders)
{
this.bidOrders = bidOrders;
}
#ManyToMany //FIXME should probably be many to many - done
public Collection<Portfolio> getPortfolios() {
return portfolios;
}
public void setPortfolios(Collection<Portfolio> portfolios) {
this.portfolios = portfolios;
}
}
#Entity
public class Portfolio
{
#Id
#GeneratedValue
private int id;
#ManyToMany
#JoinTable( name = "PortfolioMember",
#JoinColumns : #JoinColumn( name = "Portfolio_ID", referencedColumnName="id" ),
#InverseJoinColumns : #JoinColumn( name = "Member_ID", referencedColumnName="id" )
)
private List<Member> members;
}
#Entity
public class Member
{
#Id
#GeneratedValue
private int id;
#ManyToMany( mappedBy = members )
private List<Portfolio> portfolios;
}

What is root path in QueryDSL? Can you explain with an example?

I have the following two entity classes: Country and Type
#Entity
#Table(name = "countries")
public class Country {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id ;
#Column(name = "iso_code")
private String isoCode;
public Country() {
}
public Country(String isoCode) {
this.isoCode = isoCode;
}
public Country(int id, String isoCode) {
this.id = id;
this.isoCode = isoCode;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIsoCode() {
return isoCode;
}
public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}
#Override
public String toString() {
return "Country{" +
"id=" + id +
", isoCode='" + isoCode + '\'' +
'}';
}
}
#Entity
#Table(name = "types")
public class Type {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "type")
private String type;
#ManyToOne
#JoinColumn(name = "country_id")
private Country country;
#ManyToOne
#JoinColumn(name = "group_id")
private Group group;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Group getGroup() {
return group;
}
public void setGroup(int priority) {
this.group = group;
}
}
I am trying to retrieve groups using the following in the repository class:
QType qType = QType.type1;
QCountry qCountry = QCountry.country;
QGroup qGroup = QGroup.group;
QGroup qGroup1 = qType.group;
JPAQuery queryGroup = new JPAQuery(em);
QueryBase queryBaseGroups = queryGroup.from(qGroup).innerJoin(qGroup1, qGroup).innerJoin(qType.country, qCountry);
However, I get the error -
java.lang.IllegalArgumentException: Undeclared path 'type1'. Add this path as a source to the query to be able to reference it.
New to JPA. What am I doing wrong here?
So this was solved by adding qType to the from function in the query.
QueryBase queryBaseGroups = queryGroup.from(qGroup, qType).innerJoin(qGroup1, qGroup).innerJoin(qType.country, qCountry);

Why JPA select query execution returns an exception with "canot execute query" message?

The table in the database (Oracle 11g) is like this:
Name: LOG_ALIM_MAIL
Columns : ID_LOG RAW (automatically generated by SYS_GUID() in trigger), ALIMENTATION Number(9), DATE_LOG Date
PK: ID_LOG
FK: ALIMENTATION References ALIMENTATION.ID_ALIMENTATION (Number(9))
LOG_ALIM_MAIL class:
#Entity
public class LogAlimMail implements Serializable {
private static final long serialVersionUID = 2243374060845658640L;
#Id
private Long idLog;
private Date dateLog;
private Alimentation alimentation;
public LogAlimMail() {
}
public Long getIdLog() {
return idLog;
}
public void setIdLog(Long idLog) {
this.idLog = idLog;
}
public Date getDateLog() {
return dateLog;
}
public void setDateLog(Date dateLog) {
this.dateLog = dateLog;
}
#ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
public Alimentation getAlimentation() {
return alimentation;
}
public void setAlimentation(Alimentation alimentation) {
this.alimentation = alimentation;
}
}
Alimentation class:
#Entity
public class Alimentation implements Serializable {
private static final long serialVersionUID = 5790314265385194058L;
private Long idAlimentation;
private Integer etat;
public Alimentation() {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "my_alimentation_seq_gen")
#SequenceGenerator(name = "my_alimentation_seq_gen", sequenceName = "SEQ_ID_ALIMENTATION")
public Long getIdAlimentation() {
return idAlimentation;
}
public Integer getEtat() {
return etat;
}
public void setEtat(Integer etat) {
this.etat = etat;
}
public void setIdAlimentation(Long idAlimentation) {
this.idAlimentation = idAlimentation;
}
}
I've got two questions:
I'm trying to execute the following select query:
public List<LogAlimMail> getAllByIdAlim(Long idAlim) {
String request = "select a from LogAlimMail a where a.alimentation.idAlimentation = " + idAlim;
Query query = this.getEntityManager().createQuery(request);
return query.getResultList();
}
I get the Exception :
java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: idAlimentation of: administration.LogAlimMail [select a from administration.LogAlimMail a where a.alimentation.idAlimentation = 1]
I can't do the right JPA mapping between idLog (Long) and ID_LOG (RAW generated by SYS_GUID()).
Thanks
Is idAlim a number? If not, you should use idAlimentation = '" + idAlim + "'";
Or better, use bound variables:
idAlimentation = :idAlim";
query.setString("idAlim", idAlim);