I am new in hibernate, My Code is working fine but I checked that on each call of Controller class, a new connection thread has been created in mysql which goes in sleep state. My Code is -
hibernate.cfg.xml file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hib_db_netbean</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">system</property>
<property name="hibernate.dialect">org.hibernate.dialect.MariaDBDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<mapping class="com.hib.collection.UserDetails"/>
</session-factory>
</hibernate-configuration>
My Entity Class (UserDetails.java):
package com.hib.collection;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;
#Entity
#Table(name = "USER_TABLE")
public class UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int user_id;
#Column(name = "user_name")
private String username;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Controller class - CallHibernate.java
package com.hib.collection;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
#WebServlet(name = "CallHibernate", urlPatterns = {"/CallHibernate"})
public class CallHibernate extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
UserDetails user = new UserDetails();
SessionFactory sessionFactory;
Session session = null;
user.setUsername("User Name");
try (PrintWriter out = response.getWriter()) {
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
// Insert The Data In the Table
session.save(user);
session.getTransaction().commit();
session.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
session.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
MySQL Workbench Connection Status:
Use singleton design pattern for it.
Follow singleton design pattern by below link:
http://www.onlinetutorialspoint.com/hibernate/singleton-hibernate-sessionfactory-example.html
Related
I am trying to persist these two classes in oracle database using hibernate annotations and I am getting these errors.
I have two other classes which are the same and I am able to add them to the database, but this one is getting these errors.
Event Class:
package Q3;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
#Entity
#Table(name="events")
public class Event {
#Id
#Column(name="e_id" ,unique=true,nullable=false)
private int e_id;
#Column(name="event_name")
String event_name;
#ElementCollection
#CollectionTable(name="feedbacks",joinColumns=#JoinColumn(name="event_id"))
#Column(name="feed")
private Set<String> feedback;
public Event(int event_id, String event_name) {
super();
this.e_id = event_id;
this.event_name = event_name;
}
public int getEvent_id() {
return e_id;
}
public void setEvent_id(int event_id) {
this.e_id = event_id;
}
public String getEvent_name() {
return event_name;
}
public void setEvent_name(String event_name) {
this.event_name = event_name;
}
public Set<String> getFeedback() {
return feedback;
}
public void setFeedback(Set<String> feedback) {
this.feedback = feedback;
}
}
Feedback Class
package Q3;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="feedbacks")
public class Feedback {
#Id
#Column(name="f_id",unique=true,nullable=false)
private int f_id;
#Column(name="feedback")
private String feedback;
#Column(name="event_id")
private int event_id;
public Feedback(int f_id, String feedback, int event_id) {
super();
this.f_id = f_id;
this.feedback = feedback;
this.event_id = event_id;
}
public int getF_id() {
return f_id;
}
public void setF_id(int f_id) {
this.f_id = f_id;
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
public int getEvent_id() {
return event_id;
}
public void setEvent_id(int event_id) {
this.event_id = event_id;
}
}
EventMain Class
package Q3;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class EventMain {
public static void main(String[] args) {
AnnotationConfiguration config=new AnnotationConfiguration();
SessionFactory sf=config.configure
("hibernate1.cfg.xml").buildSessionFactory();
Session ses=sf.openSession();
Transaction tx=ses.beginTransaction();
ses.beginTransaction();
Feedback feed=new Feedback(1, "It was a good event. I enjoyed it a lot.", 1);
Event e=new Event(1, "WWF");
ses.save(e);
ses.save(feed);
tx.commit();
ses.close();
}
}
Error
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: insert into events (event_name, e_id) values (?, ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2395)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2858)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:178)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at Q3.EventMain.main(EventMain.java:23)
Caused by: java.sql.BatchUpdateException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:343)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10657)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 15 more
This is the config file
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="hibernate.connection.url">
jdbc:oracle:thin:#127.0.0.1:1521:ORCL
</property>
<property name="hibernate.connection.username">
hr
</property>
<property name="hibernate.connection.password">
hr
</property>
<property name="show_sql">
true
</property>
<property name="dialect">
org.hibernate.dialect.Oracle10gDialect
</property>
<property name="hibernate.hbm2ddl.auto">
update
</property>
<mapping class="Q3.Event"></mapping>
<mapping class="Q3.Feedback"></mapping>
<mapping class="Q2.Product"></mapping>
<mapping class="NEw.College"></mapping>
<mapping class="NEw.Student"></mapping>
</session-factory>
</hibernate-configuration>
I am posting everything that I have done below, so please have a look at it.
I don't know where the mistake is, and an Unknown entity error is showing. I even mapped a model in hibernate configuration file(hibernate.cfg.xml)
Resource Class in REST:
package com.tss.friends_api.user.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.tss.friends_api.user.model.User;
import com.tss.friends_api.user.service.UserService;
import com.tss.friends_api.user.service.UserServiceImpl;
#Path("user")
public class UserResource {
UserService userService=new UserServiceImpl();
#Path("/test")
#GET
#Produces(MediaType.TEXT_PLAIN)
public String createUser(){
return "user";
}
#POST
#Path("")
#Consumes(MediaType.APPLICATION_JSON)
public Response addUser(User user,#Context UriInfo uriInfo) throws Exception{
if(user==null) throw new Exception();
System.out.println(user);
String string=userService.addUser(user);
if(string!=null) {
return Response.created(uriInfo.getAbsolutePathBuilder().path(user.getUserId()+"").build()).entity("account created").build();
}
return null;
}
Model class:
package com.tss.friends_api.user.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="user_id",nullable=false)
private int userId;
#Column(name="user_name")
private String userName;
#Column(name="user_emailid")
private String userEmailId;
#Column(name="user_contactnumber")
private long userContactNumber;
#Column(name="user_password")
private String userPassword;
#OneToMany(fetch=FetchType.LAZY,targetEntity=Friends.class,cascade=CascadeType.ALL)
private List<Friends> userFriends;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmailId() {
return userEmailId;
}
public void setUserEmailId(String userEmailId) {
this.userEmailId = userEmailId;
}
public long getUserContactNumber() {
return userContactNumber;
}
public void setUserContactNumber(long userContactNumber) {
this.userContactNumber = userContactNumber;
}
public List<Friends> getUserFriends() {
return userFriends;
}
public void setUserFriends(List<Friends> userFriends) {
this.userFriends = userFriends;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
Hibernate.cgx.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/restws</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">anil4100</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping package="com.tss.friends_api.user.model"/>
</session-factory>
</hibernate-configuration>
UserService class:
package com.tss.friends_api.user.service;
import com.tss.friends_api.user.dao.UserDao;
import com.tss.friends_api.user.dao.UserDaoImpl;
import com.tss.friends_api.user.model.User;
public class UserServiceImpl implements UserService {
UserDao userDao=new UserDaoImpl();
#Override
public String addUser(User user) {
return userDao.addUser(user);
}
UserDao class:
package com.tss.friends_api.user.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.tss.friends_api.user.model.User;
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
public UserDaoImpl() {
Configuration configuration=new Configuration();
configuration.configure();
sessionFactory=configuration.buildSessionFactory();
}
#Override
public String addUser(User user) {
Session session=sessionFactory.openSession();
return session.save(user)+"";
}
and finally the error(short form):
org.hibernate.MappingException: Unknown entity: com.tss.friends_api.user.model.User
Add
sessionFactory.setPackagesToScan(new String[] { "com.tss.friends_api.user.model" });
to your sessionFactory in the UserDaoImpl.
I could imagine your Hibernate.cgx.xml gets ignored, because you build your own sessionFactory in the UserDaoImpl.
If you are using spring, have a look here .
The requirement is to fetch data from the databse and display it in dynamic report,but when i try to pass a list through createDataSource() and make a call to report.setDataSource(createDataSource()),it still display's empty value in the report,am able to display the column headers like jobid,status_value and mobile_no,but their corresponding value is empty even if the value exists in database,pls help!am i in the right path
java code
package com.unify.avcv.utils.threads;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import com.google.gson.Gson;
import com.itextpdf.text.pdf.hyphenation.TernaryTree.Iterator;
import com.unify.avcv.hibernate.util.HibernateDBUtil;
import com.unify.avcv.hibernate.model.AvcvJobData;
import net.sf.dynamicreports.jasper.builder.*;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.builder.component.TextFieldBuilder;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import java.io.File;
import java.math.BigInteger;
import org.w3c.dom.*;
import javax.activation.DataSource;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DynamicReportsGeneration {
public static void main(String[] args) throws FileNotFoundException, DRException {
try
{
JasperReportBuilder report=DynamicReports.report();
StyleBuilder boldstyle=DynamicReports.stl.style().bold();
StyleBuilder boldstyle_center=DynamicReports.stl.style(boldstyle).setHorizontalAlignment(HorizontalAlignment.CENTER);
TextFieldBuilder<String> Title=DynamicReports.cmp.text("My First Dynamic Report");
Title.setStyle(boldstyle_center);
report.title(Title);
TextColumnBuilder<String> job_id=Columns.column("jobid", "jobId", DynamicReports.type.stringType());
TextColumnBuilder<Integer> status_value=Columns.column("status_value", "status", DynamicReports.type.integerType());
TextColumnBuilder<BigInteger> mobile_value=Columns.column("mobile_no", "mobileNo", DynamicReports.type.bigIntegerType());
report.columns(job_id,status_value,mobile_value);
report.setDataSource(createDataSource());
report.show();
System.out.println("done!");
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("jobid", "status_value", "mobile_no");
Session session = (Session) HibernateDBUtil.getSessionFactory().openSession();
String avcvAuditLogQuery = "select jobId,status,mobileNo from AvcvJobData where mobileNo="+8888888811L;
List<AvcvJobData> avcvAuditLogResult = session.createQuery(avcvAuditLogQuery).list();
dataSource.add(avcvAuditLogQuery);
return dataSource;
}
}
AvcvJobData.java(POJO file)
package com.unify.avcv.hibernate.model;
import java.util.Date;
public class AvcvJobData implements java.io.Serializable, Cloneable {
private String jobId;
private Integer status;
private long mobileNo;
public AvcvJobData() {
}
public AvcvJobData(String jobId, long mobileNo) {
this.jobId = jobId;
this.mobileNo = mobileNo;
}
public AvcvJobData(String jobId, Integer status, long mobileNo
) {
this.jobId = jobId;
this.status = status;
this.mobileNo = mobileNo;
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
public long getMobileNo() {
return this.mobileNo;
}
public void setMobileNo(long mobileNo) {
this.mobileNo = mobileNo;
}
}
AvcvJobData.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.unify.avcv.hibernate.model.AvcvJobData" table="avcv_job_data" catalog="avcvmts">
<id name="jobId" type="string">
<column name="job_id" length="15" />
<generator class="assigned" />
</id>
<property name="status" type="java.lang.Integer">
<column name="status" />
</property>
<property name="mobileNo" type="long">
<column name="mobile_no" not-null="true" />
</property>
<property name="cafNo" type="string">
<column name="caf_no" length="20" />
</property>
</class>
</hibernate-mapping>
First of all you should take a look at :
TextColumnBuilder<BigInteger> mobile_value=Columns.column("mobile_no", "mobileNo", DynamicReports.type.bigIntegerType());
You declare mobile_value column that does not exist and job_id that is not a report column name.
report.columns(job_id,status_value,mobile_value);
Try this:
report.columns(jobId,status_value,mobile_no);
I'm getting this error:
java.lang.ClassNotFoundException: javax.persistence.Persistence
This is my project:
persistence.xml
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="Forum">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Model.Section</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/Forum" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
</properties>
</persistence-unit>
</persistence>
NewSectionController.java
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Section;
public class NewSectionController extends HttpServlet {
private static final long serialVersionUID = 1L;
public NewSectionController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rs = request.getRequestDispatcher("newSection.jsp");
rs.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String title = request.getParameter("titulo");
String description = request.getParameter("descricao");
Section section = new Section();
section.insertNewSection(title, description);
}
}
Section.java
package Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Persistence;
#Entity
public class Section {
#Id
#GeneratedValue
int idSection;
#Column
String titleSection;
#Column
String descriptionSection;
public void insertNewSection(String title, String description) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("Forum");
EntityManager em = factory.createEntityManager();
Section section = new Section();
section.setTitleSection(title);
section.setDescriptionSection(description);
em.getTransaction().begin();
em.persist(section);
em.getTransaction().commit();
}
public int getIdSection() {
return idSection;
}
public void setIdSection(int idSection) {
this.idSection = idSection;
}
public String getTitleSection() {
return titleSection;
}
public void setTitleSection(String titleSection) {
this.titleSection = titleSection;
}
public String getDescriptionSection() {
return descriptionSection;
}
public void setDescriptionSection(String descriptionSection) {
this.descriptionSection = descriptionSection;
}
}
The files are organized this way:
src/Controller/NewSectionController.java
src/Model/Section.java
src/META-INF/persistence.xml
resources/log4j.properties
lib/
WebContent/
And I have imported and add to build path all these libs:
antlr-2.7.7.jar
c3p0-0.9.1.jar
dom4j-1.6.1.jar
ehcache-core-2.4.3.jar
hibernate-c3p0-4.2.2.Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.2.Final.jar
hibernate-ehcache-4.2.2.Final.jar
hibernate-entitymanager-4.2.2.Final.jar
hibernate-envers-4.2.2.Final.jar
hibernate-infinispan-4.2.2.Final-tests.jar
hibernate-infinispan-4.2.2.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate-proxool-4.2.2.Final.jar
infinispan-core-5.2.0.Beta3.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-logging-3.1.1.GA.jar
jboss-marshalling-1.3.15.GA.jar
jboss-marshalling-river-1.3.15.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jgroups-3.2.0.CR1.jar
proxool-0.8.3.jar
rhq-pluginAnnotations-3.0.4.jar
slf4j-api-1.6.1.jar
stax2-api-3.1.1.jar
staxmapper-1.1.0.Final.jar
woodstox-core-asl-4.1.1.jar
And I'm still getting the java.lang.ClassNotFoundException: javax.persistence.Persistence error.
What should I do?
I used NanedQueries (as follows) in my JPA project Eclipselink as persistence provider:
#Entity
#Table(name = "login")
#NamedQueries({
#NamedQuery(name = "Login.random", query = "SELECT l FROM Login l WHERE l.pk = :randomPk"),
#NamedQuery(name = "Login.max", query = "SELECT MAX(l.pk) FROM Login l")
})
But after I change Hibernate as my persistence provider, I get the following error:
java.lang.IllegalArgumentException: org.hibernate.QueryException: unexpected char: '{' [SELECT...
I use Hibernate 3.2.5 (MySQL dialect)
Not having your exact configuration makes this difficult. But I didn't have an issue with hibernate 3.2.5.GA
I created the following Login Domain object:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name = "login")
#NamedQueries({
#NamedQuery(name = "Login.random", query = "select l FROM Login l WHERE l.pk = :randomPk"),
#NamedQuery(name = "Login.max", query = "select max(l.pk) from Login l")
})
public class Login implements Serializable {
private Long pk;
private String username;
public Login() {}
public Login(Long pk, String username) {
this.pk = pk;
this.username = username;
}
#Id
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
and test class:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import sky.sns.domain.Login;
import static org.junit.Assert.assertEquals;
public class AnnotationTest {
private static SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
#BeforeClass
public static void initialise() {
sessionFactory = new AnnotationConfiguration().configure("/hibernate-annotation.cfg.xml").buildSessionFactory();
}
#Before
public void setUp() {
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
}
#After
public void tearDown() {
transaction.rollback();
}
#Test
public void createUser() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Login persistedLogin = (Login)session.get(Login.class, 1L);
assertEquals(login.getPk(), persistedLogin.getPk());
}
#Test
public void obtainUserByIdNamedQuery() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Login persistedLogin = (Login)session.getNamedQuery("Login.random").setLong("randomPk", 1L).uniqueResult();
assertEquals(login.getPk(), persistedLogin.getPk());
}
#Test
public void obtainMaxUserIdNamedQuery() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Long maxId = (Long)session.getNamedQuery("Login.max").uniqueResult();
assertEquals(login.getPk(), maxId);
}
}
My hibernate-annotation.hbm.xml file is as follows:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.jboss.org/dtd/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_owner</property>
<property name="hibernate.connection.username">hibernate_owner</property>
<property name="hibernate.connection.password">hibernate</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable second-level cache. -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hibernate.format_sql">false</property>
<property name="hibernate.use_sql_comments">false</property>
<mapping class="sky.sns.domain.Login" />
</session-factory>
</hibernate-configuration>
Can you try this in your environment and let me know how you get on