Hello I am trying to follow this tutorial ::http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm
my code in caseyou want to have a dig is here:
https://github.com/ArthurGibbs/Centaurus-
Im using restx framework.
I am trying to use hibernate to access a local database. however when i try compile my code i get a dependency error:
src/main/java/centaurus/service/UserDao.java:7: error: package org.hibernate does not exist
import org.hibernate.HibernateException;
but i have included it in my pom so i dont understand why I am getting the error.
this is my class where there error points to
package centaurus.service;
import centaurus.entity.GameUser;
import restx.factory.Component;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
#Component
public class UserDao {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(GameUser.class).
buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
UserDao ME = new UserDao();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String email){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
GameUser employee = new GameUser();
employee.setEmail(email);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
public void saveId() {
addEmployee("bob");
}
}
new to hibernate, and not very experienced with maven. please help or let me know how to help you help me. thanks in advance
as I am using restx, it does not read the pom, it reads the md.restx.json file where i was missing the dependencies dependancies
Related
This is the actual error I'm getting:
NoInitialContextException: Need to specify class name in environment or system property
I'm trying to have a datasource connection working on a project without servlet but just a main to launch.
This is the main class:
package pacchetto;
import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class testIt {
public static void main(String[] args) throws SQLException, NamingException {
Context ctx = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
Connection con = ds.getConnection();
try {
con = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null)
System.out.println("Connessione riuscita");
}
}
}
In the same project I also have a servlet file and using it everything works fine. This led me to thinking that the problem must be in this class and not in the servlet.xml or any other configuration file. Should I be wrong and should you need the whole scene I'll be happy to paste them here along with the main.
What am I doing wrong?
I have written the following code but its showing a compile time error that -
Transaction could not be resolved to a type
Even though I have imported org.hibernate.Transaction.
Could you please help. Following is my code:
package mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Mainclass {
public static void main(String[] args) {
//creating configuration object
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t= (Transaction)session.beginTransaction();
Employee e1=new Employee();
e1.setId(115);
e1.setFirstName("sonoo");
e1.setLastName("jaiswal");
session.persist(e1);//persisting the object
try {
t.commit();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.close();
System.out.println("successfully saved");
}
}
There is nothing wrong with the code as written. It should compile. There is a type called org.hibernate.Transaction - it is an interface.
So why might this not compile?
Maybe the above one isn't the version of the source code that you are compiling.
Maybe the compiler's build classpath is incorrect.
Maybe you are somehow mixing up the versions of the hibernate JAR files, and / or you are missing the JAR that contains >>that<< class.
My question is, if the method "begin()" is capable of lock a thread further than the "timeout" config in the persistence.xml.
Here is a snippet:
#Inject EntityManager em;
#Inject ContextControl ctxCtrl;
String fileType;
String fileName;
String hash;
BufferedReader reader = null;
public void run(File f, String fileType, String hash) throws ProcessorException, IOException{
this.fileType = fileType;
this.hash= hash;
this.fileName = f.getName();
try {
ctxCtrl.startContext(RequestScoped.class);
em.getTransaction().begin();
reader = openReader(f);
//rest of the code...
em.getTransaction().commit();
}catch (Exception e) {
logger.error(e.getMessage(), e);
try{ //for database breakdown purpose
em.getTransaction().rollback();
}catch(Exception e2){
logger.error(e2.getMessage(), e2);
throw new ProcessorException();
}
throw new ProcessorException();
}finally{
reader.close();
ctxCtrl.stopContext(RequestScoped.class);
}
"run" method is executed inside a loop. This method is executed serially, there is no possible concurrency.
Now, the thing is that the thread stops randomly at line "em.getTransaction().begin();", with no exception. And since this is a critical area, all the application is stopped and the lock is never released.
The only thing I can think of is the "begin()" method getting stuck somehow, but not in an exception way, but rather in a lock way (since no exception is caught).
I wasn't able to recreate the issue, I can only say that the issue has nothing to do with the file. Also, this is happening in production, so I can't debug the application other than check some logs
thanks in advance
EDIT
I use Deltaspike to provide the CDI. Entitymanager it's injected anytime it's needed. It's created like this:
CLASS ENTITYMANAGER FACTORY PRODUCER
import java.io.FileInputStream;
import java.util.Properties;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
#ApplicationScoped
public class EntityManagerFactoryProducer {
#Inject Logger logger;
#Produces
#ApplicationScoped
public EntityManagerFactory create() {
Properties props = new Properties();
try {
props.load(new FileInputStream("cfg/connection.properties"));
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return Persistence.createEntityManagerFactory("scgach",props);
}
public void destroy(#Disposes EntityManagerFactory factory) {
factory.close();
}
}
CLASS ENTITYMANAGER PRODUCER
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
#ApplicationScoped
public class EntityManagerProducer {
#Inject EntityManagerFactory emf;
#Produces #RequestScoped
public EntityManager create() {
return emf.createEntityManager();
}
public void destroy(#Disposes EntityManager em) {
if(em.isOpen())
em.close();
}
}
I have a code that works fine. The important parts are as follows:
My model class:
package biz.tugay.sakila.model;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:48 */
public class Actor {
private long id;
private String firstName;
private String lastName;
// Getters, setters...
}
My dao class:
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:12 */
import biz.tugay.sakila.model.Actor;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ActorDao {
protected static final Connection connection = DBConnector.getConnection();
public List<Actor> getAllActors() throws SQLException {
List<Actor> allActors = new ArrayList<Actor>();
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM Actor";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
// You get the idea... Setters again..
allActors.add(actor);
}
rs.close();
stmt.close();
return allActors;
}
}
and the DBConnector
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:35 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnector {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/sakila";
static final String USER = "root";
static final String PASS = "";
private static Connection connection = null;
public static final Connection getConnection() {
if (connection != null) {
return connection;
} else {
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASS);
return connection;
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
throw new UnsupportedOperationException();
}
}
}
My Servlet class:
package biz.tugay.sakila.servlet;
/* User: koray#tugay.biz Date: 26/06/15 Time: 14:31 */
import biz.tugay.sakila.dao.ActorDao;
import biz.tugay.sakila.model.Actor;
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 java.io.IOException;
import java.sql.SQLException;
import java.util.List;
#WebServlet(urlPatterns = "/actors")
public class ActorServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ActorDao actorDao = new ActorDao();
List<Actor> allActors = null;
try {
allActors = actorDao.getAllActors();
req.setAttribute("allActors",allActors);
req.getRequestDispatcher("/actors.jsp").forward(req, resp);
} catch (SQLException e) {
}
}
}
And /actors.jsp will show an HTML table to the user.
I have made this exercise myself with the sakila sample database MySQL provides.
My question is, without using any framework such as Spring or Struts, how can I achieve a better separation? For example, currently ActorServlet depends on ActorDao concretely, can I fix this, if so how? Also ActorDao depends heavily on DBConnector. For example, I want to be able to create a NoSQL connector and use it, but currently I can not I guess?
First step is to abstract out some interfaces. For example, make ActorDao an interface, move the implementation to ActorDaoImpl or whatever. Create an ActorDaoFactory that hands you an ActorDao which is, under the covers, an ActorDaoImpl, but the servlet doesn't need to know that.
Second step is more complex... if you want to only use Tomcat, then injection and the like is out, but you can configure Tomcat to create these new interfaces and put them in JNDI. This process is probably too complex to put in an answer here, but the Tomcat documentation on JNDI is really nice. The process basically involves creating a factory, like I advocated above, and then having Tomcat invoke that factory through configuration.
Once you do this, looking them up from JNDI is as simple as
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our DAO
ActorDao ad = (ActorDao)envCtx.lookup("dao/actor");
Good luck!
I am getting the title error while compiling my java file. But I am not getting where is my mistake..Can anyone please help me? Below is my code:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
//imported UserDetailInfo class also here..
public class UserInfo {
public static void main(String[] args){
Session session=null;
try{
UserDetailInfo demopojo=new UserDetailInfo();
Configuration configuration = new Configuration();
SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
transaction.begin();
demopojo.setId(1);
demopojo.setFirstName("Johny");
demopojo.setLastName("John");
session.save(demopojo);
transaction.commit();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
session.close();
}
}
}
i had the same problem try to remove
#SuppressWarnings("serial")
if you have it above main class. it worked for me.