How to map an entity with JPA? - java

I have a table called fund, I would like to use JPA in order to write my own queries for it. So, I have use IntelliJ to generate persistence mapping based on my schema and not based on hibernate.
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table(name = "fund", schema = "public", catalog = "db")
public class FundEntity {
private long fundId;
private Timestamp createdAt;
private String description;
private Timestamp modTime;
private String modUser;
private String fundName;
private String fundType;
#Id
#Column(name = "fund_id")
public long getFundId() {
return fundId;
}
public void setFundId(long fundId) {
this.fundId = fundId;
}
#Basic
#Column(name = "created_at")
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
#Basic
#Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Basic
#Column(name = "mod_time")
public Timestamp getModTime() {
return modTime;
}
public void setModTime(Timestamp modTime) {
this.modTime = modTime;
}
#Basic
#Column(name = "mod_user")
public String getModUser() {
return modUser;
}
public void setModUser(String modUser) {
this.modUser = modUser;
}
#Basic
#Column(name = "fund_name")
public String getFundName() {
return fundName;
}
public void setFundName(String fundName) {
this.fundName = fundName;
}
#Basic
#Column(name = "fund_type")
public String getFundType() {
return fundType;
}
public void setFundType(String fundType) {
this.fundType = fundType;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FundEntity that = (FundEntity) o;
if (fundId != that.fundId) return false;
if (createdAt != null ? !createdAt.equals(that.createdAt) : that.createdAt != null) return false;
if (description != null ? !description.equals(that.description) : that.description != null) return false;
if (modTime != null ? !modTime.equals(that.modTime) : that.modTime != null) return false;
if (modUser != null ? !modUser.equals(that.modUser) : that.modUser != null) return false;
if (fundName != null ? !fundName.equals(that.fundName) : that.fundName != null) return false;
if (fundType != null ? !fundType.equals(that.fundType) : that.fundType != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (fundId ^ (fundId >>> 32));
result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (modTime != null ? modTime.hashCode() : 0);
result = 31 * result + (modUser != null ? modUser.hashCode() : 0);
result = 31 * result + (fundName != null ? fundName.hashCode() : 0);
result = 31 * result + (fundType != null ? fundType.hashCode() : 0);
return result;
}
}
And this is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence-unit name="postgres">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5443/db" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.connection.username" value="dba" />
<property name="hibernate.connection.password" value="XXX" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
Then I try to fetch my funds but with no results:
jpa-ql> select f from FundEntity f
[2016-06-29 18:01:11] FundEntity is not mapped [select f from FundEntity f]
What am I missing here ? I thought the discovery for my entities would be made automatically since I have specified on my persistence.xml file.

If your #Entity class is not in the same classpath as the persistence.xml file, it will not be automatically loaded. For example -
Is there a way to scan JPA entities not to declare persistent classes in a persistence.xml file?

Related

Java ee, JPA 2.1 retruning null

frist of all sorry for my bad english. I am trying to display database (Postgres) rows from one table, and it allways returning null. I am doing project in Java EE using JPA hibernate.
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="mesPU">
<class>pl.mes.model.Users</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/test" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="xxxxxx" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/test"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
</properties>
</persistence-unit>
</persistence>
Users entity
package pl.mes.model;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Users {
private Integer userId;
private String firstname;
private String secondname;
private String email;
#Id
#Column(name = "userId", nullable = false)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
#Basic
#Column(name = "firstname", nullable = true)
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Basic
#Column(name = "secondname", nullable = true)
public String getSecondname() {
return secondname;
}
public void setSecondname(String secondname) {
this.secondname = secondname;
}
#Basic
#Column(name = "email", nullable = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Users users = (Users) o;
if (userId != null ? !userId.equals(users.userId) : users.userId != null) return false;
if (firstname != null ? !firstname.equals(users.firstname) : users.firstname != null) return false;
if (secondname != null ? !secondname.equals(users.secondname) : users.secondname != null) return false;
if (email != null ? !email.equals(users.email) : users.email != null) return false;
return true;
}
#Override
public int hashCode() {
int result = userId != null ? userId.hashCode() : 0;
result = 31 * result + (firstname != null ? firstname.hashCode() : 0);
result = 31 * result + (secondname != null ? secondname.hashCode() : 0);
result = 31 * result + (email != null ? email.hashCode() : 0);
return result;
}
}
When i use this
select u from Users u
in console output looks like that:
output
DbSOURCE
I would be grateful if someone can help me with this :)
You have specified the URL jdbc:postgresql://localhost:5432/test for the property javax.persistence.jdbc.url. But when I look at the second screenshot, I can not see a database schema named test.
I guess, you are connecting to the wrong database. Maybe a second instance listening at a different port?
Please also remove the Hibernate specific properties that are already specified by JPA standard properties (as stated out in the comments by Billy Frost).

Spring DATA JPA + Hibernate - could not initialize proxy - no Session after fix:

Good day, all. I'm newbie in Spring Data + JPA. And i need your help.
It's my first question on stackoverflow, that sorry if i formed my Question not correct.
I start to realise project using Spring Data + JPA + Hibernate, Spring MVC, Use MySQL.
I have DB scheme:
DB of project
DB scheme
application context:
<context:property-placeholder location="classpath:util.properties" />
<!--Activates various annotations to be detected in bean classes: Spring's #Required and #Autowired and so on-->
<context:annotation-config/>
<!-- Datasource. - MySQL -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}" />
</bean>
<!--Do not forget activate #Transactional JPA annotation with <annotation-driven/>-->
<!-- JPA Persistence Context and EntityManager configuration -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<!--packagesToScan - search Entity and mapping them -->
<property name="packagesToScan" value="by.GetItFree" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
</bean>
<!-- Automatic Transaction Participation-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<jpa:repositories base-package="by.GetItFree.orm.repository" entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"/>
MVC Config:
<!--
mvc:annotation-driven configures Spring MVC annotations
Support for validating #Controller inputs with #Valid, if a JSR-303 Provider is present on the classpath.
HttpMessageConverter support for #RequestBody method parameters and #ResponseBody method return values
from #RequestMapping or #ExceptionHandler methods.
-->
<mvc:annotation-driven/>
<!-- activate #Transactional JPA annotation -->
<tx:annotation-driven/>
<!-- ViewResolver bean config for mapping strings to jsp views -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
<property name="order" value="1" />
<property name="prefix" value="/WEB-INF/view" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/about.html" view-name="/about/about"/>
<mvc:view-controller path="/index.html" view-name="/index"/>
<!-- Static Resources Configuration (get access to static sources such as CSS and JavaScript files) -->
<mvc:resources mapping="/resources/**" location="/resources/" />
Some of JPA Persistence Entites:
Advert:
#Entity
public class Advert {
private int id;
private String karmaReq;
private byte[] image;
private int profileId;
private String profileUsersUsername;
private String head;
private String content;
private byte ordered;
private Timestamp date;
private Profile profile;
private Collection<Comment> commentsById;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "karmaReq", nullable = true, length = 45)
public String getKarmaReq() {
return karmaReq;
}
public void setKarmaReq(String karmaReq) {
this.karmaReq = karmaReq;
}
#Basic
#Column(name = "image", nullable = false)
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Basic
#Column(name = "profile_id", nullable = false)
public int getProfileId() {
return profileId;
}
public void setProfileId(int profileId) {
this.profileId = profileId;
}
#Basic
#Column(name = "profile_users_username", nullable = false, length = 45)
public String getProfileUsersUsername() {
return profileUsersUsername;
}
public void setProfileUsersUsername(String profileUsersUsername) {
this.profileUsersUsername = profileUsersUsername;
}
#Basic
#Column(name = "head", nullable = true, length = 45)
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
#Basic
#Column(name = "content", nullable = true, length = 450)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Basic
#Column(name = "ordered", nullable = false)
public byte getOrdered() {
return ordered;
}
public void setOrdered(byte ordered) {
this.ordered = ordered;
}
#Basic
#Column(name = "date", nullable = false)
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Advert advert = (Advert) o;
if (id != advert.id) return false;
if (profileId != advert.profileId) return false;
if (ordered != advert.ordered) return false;
if (karmaReq != null ? !karmaReq.equals(advert.karmaReq) : advert.karmaReq != null) return false;
if (!Arrays.equals(image, advert.image)) return false;
if (profileUsersUsername != null ? !profileUsersUsername.equals(advert.profileUsersUsername) : advert.profileUsersUsername != null)
return false;
if (head != null ? !head.equals(advert.head) : advert.head != null) return false;
if (content != null ? !content.equals(advert.content) : advert.content != null) return false;
if (date != null ? !date.equals(advert.date) : advert.date != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (karmaReq != null ? karmaReq.hashCode() : 0);
result = 31 * result + Arrays.hashCode(image);
result = 31 * result + profileId;
result = 31 * result + (profileUsersUsername != null ? profileUsersUsername.hashCode() : 0);
result = 31 * result + (head != null ? head.hashCode() : 0);
result = 31 * result + (content != null ? content.hashCode() : 0);
result = 31 * result + (int) ordered;
result = 31 * result + (date != null ? date.hashCode() : 0);
return result;
}
#ManyToOne
#JoinColumns({#JoinColumn(name = "profile_id", referencedColumnName = "id", nullable = false, insertable = false, updatable = false), #JoinColumn(name = "profile_users_username", referencedColumnName = "users_username", nullable = false, insertable = false, updatable = false)})
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
#OneToMany(mappedBy = "advertByAdvertId")
public Collection<Comment> getCommentsById() {
return commentsById;
}
public void setCommentsById(Collection<Comment> commentsById) {
this.commentsById = commentsById;
}
#Override
public String toString() {
return "Advert{" +
"id=" + id +
", karmaReq='" + karmaReq + '\'' +
", image=" + Arrays.toString(image) +
", profileId=" + profileId +
", profileUsersUsername='" + profileUsersUsername + '\'' +
", head='" + head + '\'' +
", content='" + content + '\'' +
", ordered=" + ordered +
", date=" + date +
", profile=" + profile +
", commentsById=" + commentsById +
'}';
}
}
// I know , that if i comment call profile in to String(), all will be work.
Profile
#Entity
#IdClass(ProfilePK.class)
public class Profile {
private int id;
private String usersUsername;
private Integer karma;
private String phone;
private byte[] icon;
private Collection<Advert> adverts;
private Collection<Comment> comments;
private Collection<Message> messages;
private Users usersByUsersUsername;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Id
#Column(name = "users_username", nullable = false, length = 45)
public String getUsersUsername() {
return usersUsername;
}
public void setUsersUsername(String usersUsername) {
this.usersUsername = usersUsername;
}
#Basic
#Column(name = "karma", nullable = true)
public Integer getKarma() {
return karma;
}
public void setKarma(Integer karma) {
this.karma = karma;
}
#Basic
#Column(name = "phone", nullable = true, length = 15)
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Basic
#Column(name = "icon", nullable = true)
public byte[] getIcon() {
return icon;
}
public void setIcon(byte[] icon) {
this.icon = icon;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Profile profile = (Profile) o;
if (id != profile.id) return false;
if (usersUsername != null ? !usersUsername.equals(profile.usersUsername) : profile.usersUsername != null)
return false;
if (karma != null ? !karma.equals(profile.karma) : profile.karma != null) return false;
if (phone != null ? !phone.equals(profile.phone) : profile.phone != null) return false;
if (!Arrays.equals(icon, profile.icon)) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (usersUsername != null ? usersUsername.hashCode() : 0);
result = 31 * result + (karma != null ? karma.hashCode() : 0);
result = 31 * result + (phone != null ? phone.hashCode() : 0);
result = 31 * result + Arrays.hashCode(icon);
return result;
}
#OneToMany(mappedBy = "profile")
public Collection<Advert> getAdverts() {
return adverts;
}
public void setAdverts(Collection<Advert> adverts) {
this.adverts = adverts;
}
#OneToMany(mappedBy = "profile")
public Collection<Comment> getComments() {
return comments;
}
public void setComments(Collection<Comment> comments) {
this.comments = comments;
}
#OneToMany(mappedBy = "profile")
public Collection<Message> getMessages() {
return messages;
}
public void setMessages(Collection<Message> messages) {
this.messages = messages;
}
#ManyToOne
#JoinColumn(name = "users_username", referencedColumnName = "username", nullable = false, insertable = false, updatable = false)
public Users getUsersByUsersUsername() {
return usersByUsersUsername;
}
public void setUsersByUsersUsername(Users usersByUsersUsername) {
this.usersByUsersUsername = usersByUsersUsername;
}
#Override
public String toString() {
return "Profile{" +
"id=" + id +
", usersUsername='" + usersUsername + '\'' +
", karma=" + karma +
", phone='" + phone + '\'' +
", icon=" + Arrays.toString(icon) +
", adverts=" + adverts +
", comments=" + comments +
", messages=" + messages +
", usersByUsersUsername=" + usersByUsersUsername +
'}';
}
}
ORM
AdvertDAO
/**
* DAO interface responsible for operation with Advertising.
* <p>
* Created by Novik Igor on 09.02.2017.
*/
public interface AdvertDAO {
/**
* Method returned list of Advert's from the DB.
*
* #return list of Advertising's.
*/
List<Advert> findAll();
/**
* Method returned list of Advert from the DB according ID.
*
* #param head id of the Advert;
* #return Advertising according id.
*/
Advert findByHead(String head);
}
AdvertDAORepository
/**
* SpringData AdvertDAO repository.
*
* Created by Novik Igor on 10.02.2017.
*/
public interface AdvertDAORepository extends CrudRepository<Advert,Integer> {
List<Advert> findByHead(String head);
}
Service for Spring Data/JPA - AdvertDAOImpl
/**
* Repository bean that implements JPA DAO Advert interfaces responsible for operation with Advertising from DB.
* <p>
* Created by nolik on 10.02.17.
*/
#Service("jpaAdvertDAO")
#Repository
#Transactional
public class AdvertDAOImpl implements AdvertDAO {
#Autowired
private AdvertDAORepository advertDAORepository;
#Override
public List<Advert> findAll() {
return Lists.newArrayList(advertDAORepository.findAll());
}
#Override
public Advert findByHead(String head) {
return (Advert) advertDAORepository.findByHead(head);
}
}
Test MVC Controller:
#Controller
public class TestController {
#Autowired
AdvertDAO jpaAdvertDAO;
#Autowired
CommentDAO jpaCommentDAO;
#RequestMapping(value = "/testCall", method = RequestMethod.GET)
public ModelAndView readCookieExample() {
System.out.println(" Test console");
return new ModelAndView("/error/errorpage");
}
#RequestMapping(value = "/jpaFindAllAdvert", method = RequestMethod.GET)
public ModelAndView jpaFindAllAdvert() {
System.out.println("ORMController ormFindAllUsers is called");
List<Advert> adverts = jpaAdvertDAO.findAll();
return new ModelAndView("/error/test", "resultObject", adverts);
}
#RequestMapping(value = "/jpaFindAllComments", method = RequestMethod.GET)
public ModelAndView jpaFindAllComments() {
System.out.println("ORMController FindAllComments is called");
List<Comment> comments = jpaCommentDAO.findAll();
return new ModelAndView("/error/test", "resultObject", comments);
}
}
Simple JSP for showing result of calling "/jpaFindAllAdvert"
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Test</title>
</head>
<body>
<%--Find All Adverts--%>
${resultObject}
</body>
</html>
Firstly i faced with the next exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: by.GetItFree.entities.Profile.adverts, could not initialize proxy - no Session
org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:563)
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:205)
org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:542)
org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:133)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:509)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Profile.toString(Profile.java:144)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Advert.toString(Advert.java:174)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
java.util.AbstractCollection.toString(AbstractCollection.java:462)
org.apache.el.lang.ELSupport.coerceToString(ELSupport.java:497)
org.apache.el.lang.ELSupport.coerceToType(ELSupport.java:529)
org.apache.el.ExpressionFactoryImpl.coerceToType(ExpressionFactoryImpl.java:47)
javax.el.ELContext.convertToType(ELContext.java:304)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:944)
org.apache.jsp.WEB_002dINF.view.error.test_jsp._jspService(test_jsp.java:118)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1271)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
I google that it's a result of N+1 SQL problem for Hibernate for Leazy initialisation of Joined with #ManyToONe relations.
I use way to fix with adding:
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
to "Jpa Properties"
After this i faced with: StackOverflow exeption:
java.lang.StackOverflowError
java.util.AbstractCollection.toString(AbstractCollection.java:454)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:510)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Profile.toString(Profile.java:144)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Advert.toString(Advert.java:174)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
java.util.AbstractCollection.toString(AbstractCollection.java:462)
org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:510)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Profile.toString(Profile.java:144)
java.lang.String.valueOf(String.java:2994)
java.lang.StringBuilder.append(StringBuilder.java:131)
by.GetItFree.entities.Advert.toString(Advert.java:174)
Etc.. - very long listing
In Tocat Log in the last case - i see big listing JPQL/or HSQL i'm not shure:
RMController ormFindAllUsers is called
Hibernate: select advert0_.id as id1_1_, advert0_.content as content2_1_, advert0_.date as date3_1_, advert0_.head as head4_1_, advert0_.image as image5_1_, advert0_.karmaReq as karmaReq6_1_, advert0_.ordered as ordered7_1_, advert0_.profile_users_username as profile_9_1_, advert0_.profile_id as profile_8_1_ from Advert advert0_
Hibernate: select profile0_.users_username as users_us1_5_0_, profile0_.id as id2_5_0_, profile0_.icon as icon3_5_0_, profile0_.karma as karma4_5_0_, profile0_.phone as phone5_5_0_, users1_.username as username1_6_1_, users1_.enabled as enabled2_6_1_, users1_.password as password3_6_1_ from Profile profile0_ inner join Users users1_ on profile0_.users_username=users1_.username where profile0_.users_username=? and profile0_.id=?
Hibernate: select adverts0_.profile_users_username as profile_9_1_0_, adverts0_.profile_id as profile_8_1_0_, adverts0_.id as id1_1_0_, adverts0_.id as id1_1_1_, adverts0_.content as content2_1_1_, adverts0_.date as date3_1_1_, adverts0_.head as head4_1_1_, adverts0_.image as image5_1_1_, adverts0_.karmaReq as karmaReq6_1_1_, adverts0_.ordered as ordered7_1_1_, adverts0_.profile_users_username as profile_9_1_1_, adverts0_.profile_id as profile_8_1_1_ from Advert adverts0_ where adverts0_.profile_users_username=? and adverts0_.profile_id=?
Hibernate: select profile0_.users_username as users_us1_5_0_, profile0_.id as id2_5_0_, profile0_.icon as icon3_5_0_, profile0_.karma as karma4_5_0_, profile0_.phone as phone5_5_0_, users1_.username as username1_6_1_, users1_.enabled as enabled2_6_1_, users1_.password as password3_6_1_ from Profile profile0_ inner join Users users1_ on profile0_.users_username=users1_.username where profile0_.users_username=? and profile0_.id=?
My progect on github: ProgectSourceCode
What's the reason of this behaiviour. And what's the solution?
Thx for your attention and support.
The reason you're having this problem is because associations that your view requires should be initialized inside a transaction boundary to avoid the LazyInitializationException. Adding an option to load collections outside of a transaction is merely a bandaid and doesn't truly address the underlying design flaw of your code.
If your view requires that you load Profile and its associated collection of Advert entities, then your either your data access should should specifically toggle that behavior or the query specify that you need that collection initialized.
There are a number of ways you can trigger this collection to be loaded as part of a query.
JPQL/HQL using a JOIN FETCH on the adverts collection.
Specify a join fetch using the Criteria API
Use #FetchProfile to toggle a specific fetch strategy by name.
Use #NamedEntityGraph.

Hibernate not using defined sequence (postgresql)

I'm trying to insert mapped object to postgresql database with correct id. This is how i insert:
Session session = Main.getSession();
Transaction rx = session.beginTransaction();
ProductsEntity productsEntity = new ProductsEntity();
productsEntity.setName(nameTextField.getText());
productsEntity.setDescription(descriptionTextArea.getText());
productsEntity.setCategory((ProductCategoriesEntity) categoryComboBox.getSelectedItem());
productsEntity.setPrice(new BigDecimal(1.0));
session.save(productsEntity);
tx.commit();
session.close();
Class with defined sequence:
#Entity
#Table(name = "products", schema = "public", catalog = "shop")
public class ProductsEntity {
private int id;
private String name;
private String description;
private BigDecimal price;
#Id
#Column(name = "id", nullable = false)
#SequenceGenerator(name="pk_sequence",sequenceName="products_id_seq")
#GeneratedValue(strategy=GenerationType.AUTO,generator="pk_sequence")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = false, length = -1)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "description", nullable = false, length = -1)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Basic
#Column(name = "price", nullable = false, precision = 2)
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductsEntity that = (ProductsEntity) o;
if (id != that.id) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (description != null ? !description.equals(that.description) : that.description != null) return false;
if (price != null ? !price.equals(that.price) : that.price != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (price != null ? price.hashCode() : 0);
return result;
}
private ProductCategoriesEntity category;
#ManyToOne
public ProductCategoriesEntity getCategory() {
return category;
}
public void setCategory(ProductCategoriesEntity category) {
this.category = category;
}
}
Last value of postgresql sequence products_id_seq is 4. Hibernate is inserting object with id=0, so first insert was successful, now I'm getting unique constraint violation.
EDIT
I've made sequence work by adding generator
<generator class="identity"/>
in xml mapping definition
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="entities.ProductsEntity" table="products" schema="public" catalog="shop">
<id name="id">
<column name="id" sql-type="integer"/>
<generator class="identity"/>
</id>
<property name="name">
<column name="name" sql-type="varchar"/>
</property>
<property name="description">
<column name="description" sql-type="varchar"/>
</property>
<property name="price">
<column name="price" sql-type="numeric(9,2)" precision="9" scale="2"/>
</property>
<many-to-one name="category" column="category_id" class="entities.ProductCategoriesEntity" lazy="false"/>
</class>
</hibernate-mapping>
This works without defining sequence in class. I've also tried to use
#GeneratedValue(strategy=GenerationType.IDENTITY)
in class file but it doesn't work.
If someone has an idea please tell me why only "xml" method works.
Is the sequence "products_id_seq" a DB Sequence?
If Yes, then change your GenerationType from Auto to SEQUENCE.
I've a similar setup with Postgres and setting GenerationType as SEQUENCE and giving allocationSize = 1 worked for me.
Also, ensure your sequence is upto date with the table. If not, Alter the sequence for now so your further updates will not fail.

persistence and Hibernate errors in spring boot JPA

persistenceUnit/Hibernate
Connection to persistenceUnit/Hibernate failed
Could not create connection to database server. Attempted reconnect 3 times
I have this error and when i go to jpa console and run commands, i get this:
access denied for user 'root'#'localhost' (using password: YES)
Despite, i can see my database in database tab in intellij. And also it created entityclass.
So, why do i have those errors?
It did not create persistance.xml so i created it and put to src/web-inf
<persistence-unit name="persistenceUnit">
<class>models.MovieEntity</class>
<properties>
<property name="eclipselink.jdbc.url" value="jdbc:mysql://localhost:3306/mysql"/>
<property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.jdbc.user"/>
<property name="eclipselink.jdbc.password"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/mysql"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username"/>
<property name="hibernate.connection.password"/>
<property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/mysql"/>
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionUserName"/>
<property name="openjpa.ConnectionPassword"/>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/mysql"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.user"/>
<property name="toplink.jdbc.password"/>
</properties>
</persistence-unit>
it generated those lines but sone of them are red, errors. SAme password for all for example?
Also, i get those errors:
ava.lang.RuntimeException: org.hibernate.AnnotationException: No identifier specified for entity: com.models.MovieEntity
at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:277)
at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:224)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
my entity
#Entity
#Table(name = "movie", schema = "mysql", catalog = "")
public class MovieEntity {
private int id;
private String title;
private String actors;
#Basic
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Id
#Column(name = "Title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Basic
#Column(name = "Actors")
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MovieEntity that = (MovieEntity) o;
if (id != that.id) return false;
if (title != null ? !title.equals(that.title) : that.title != null) return false;
if (actors != null ? !actors.equals(that.actors) : that.actors != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (actors != null ? actors.hashCode() : 0);
return result;
}
}
entity class gives error of no catalog.
Seen the your configuration I can see that you have the username and password empty, now probably the persistance.xml that you are posted was a example bat one of your error access denied for user 'root'#'localhost' (using password: YES) follow me to advice you to check if your database was configured with a password and use it (I'm not crazy in a standard installation without configuration on linux many times I had empty password). Then I can see that you have #Id on title properties when probably the your sql for tabel generation, requires that id was the primary key.
I hope that this can help you
The database seems to be missing in the connection string
Most likely your Entity has no field annotated with #Id
Your actual error is :
No identifier specified for entity: com.models.MovieEntity
You must specify an id in com.models.MovieEntity class
#javax.persistence.Id
private Long id;

Trouble working with EntityManagerFactory

I'm trying to figure out how to use #PersistenceUnit as I've read it's a much better solution than #PersistenceContext. The trouble is.... I can't figure out how to get it to work properly...
#Controller
public class Content {
#PersistenceUnit(unitName = "CMTPU")
public EntityManagerFactory emf;
public EntityManager em = emf.createEntityManager();
#RequestMapping(value={"/content/edit*"}, method=RequestMethod.GET)
public ModelAndView edit(Model model) {
ModelAndView mv = new ModelAndView();
mv.setViewName("content/edit");
//get symbols
List<Symbol> symbols = em.createNamedQuery("Symbol.findAll").getResultList();
mv.addObject(symbols);
return mv;
}
}
My app loaded before I added the //get symbols section and the EntityManager stuff. Now I'm seeing the error SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.NullPointerException
I've read that I need to define a unitName, but then I'm looking at this documentation and it doesn't show that being done.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="CMTPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>CMT_DEV</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
I'm having trouble determining what I'm doing wrong.
update
My model defines the database and all of that as seen below. Do I even need a persistence.xml?
package com.fettergroup.cmt.models;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "symbol", catalog = "DATABASE1", schema = "dbo")
#NamedQueries({
#NamedQuery(name = "Symbol.findAll", query = "SELECT s FROM Symbol s"),
#NamedQuery(name = "Symbol.findById", query = "SELECT s FROM Symbol s WHERE s.id = :id"),
#NamedQuery(name = "Symbol.findBySymbol", query = "SELECT s FROM Symbol s WHERE s.symbol = :symbol"),
#NamedQuery(name = "Symbol.findByHtmlNumber", query = "SELECT s FROM Symbol s WHERE s.htmlNumber = :htmlNumber"),
#NamedQuery(name = "Symbol.findByHtmlName", query = "SELECT s FROM Symbol s WHERE s.htmlName = :htmlName"),
#NamedQuery(name = "Symbol.findByAsciiDec", query = "SELECT s FROM Symbol s WHERE s.asciiDec = :asciiDec"),
#NamedQuery(name = "Symbol.findByAsciiHex", query = "SELECT s FROM Symbol s WHERE s.asciiHex = :asciiHex")})
public class Symbol implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Short id;
#Size(max = 10)
#Column(name = "symbol")
private String symbol;
#Size(max = 10)
#Column(name = "html_number")
private String htmlNumber;
#Size(max = 10)
#Column(name = "html_name")
private String htmlName;
#Size(max = 10)
#Column(name = "ascii_dec")
private String asciiDec;
#Size(max = 10)
#Column(name = "ascii_hex")
private String asciiHex;
public Symbol() {
}
public Symbol(Short id) {
this.id = id;
}
public Short getId() {
return id;
}
public void setId(Short id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getHtmlNumber() {
return htmlNumber;
}
public void setHtmlNumber(String htmlNumber) {
this.htmlNumber = htmlNumber;
}
public String getHtmlName() {
return htmlName;
}
public void setHtmlName(String htmlName) {
this.htmlName = htmlName;
}
public String getAsciiDec() {
return asciiDec;
}
public void setAsciiDec(String asciiDec) {
this.asciiDec = asciiDec;
}
public String getAsciiHex() {
return asciiHex;
}
public void setAsciiHex(String asciiHex) {
this.asciiHex = asciiHex;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Symbol)) {
return false;
}
Symbol other = (Symbol) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.project1.models.Symbol[ id=" + id + " ]";
}
}
use only
#Controller
public class Content {
#PersistenceContext(unitName = "CMTPU")
public EntityManager em;
The entity manager should be controlled by spring.
This ins an example, it uses hiberante as persistence provider, but I think you can adapt it.
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="myPersistenceUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
</bean>
sample persistance unit, that works with that configuration
<persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.connection.charSet" value="UTF-8" />
</properties>
</persistence-unit>

Categories

Resources