"Could not locate cfg.xml resource [hibernate.cfg.xml]" error - sql

When I run my createStudentDemo class I get the following error:
INFO: HHH000412: Hibernate Core {5.4.11.Final}
Exception in thread "main"
org.hibernate.internal.util.config.ConfigurationException: Could not
locate cfg.xml resource [hibernate.cfg.xml] at
org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53) at
org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:215) at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
at org.hibernate.cfg.Configuration.configure(Configuration.java:244)
at
com.luv2code.hibernate.demo.CreateStudentDemo.main(CreateStudentDemo.java:15)
I don't understand why I have this error.
Here is the code of my createStudentDemo class:
package com.luv2code.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory= new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
//create a student object
System.out.println("creating new student object");
Student tempStudent = new Student("Paul", "Wall", "paul#luv2code.com");
//start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
//commit transaction
session.getTransaction().commit();
System.out.println("Done !");
}
finally {
factory.close();
}
}
}
and here is the code for my class student:
package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
public Student() {
}
#Id
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
and here is the code of my hibernate.cfg.xml file:
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
and here is the location of my files:
Can someone help me please?

You hibernate.cfg.xml should be in classpath. Put it in src folder.

Related

How to solve this issue about Java DB connection

There are my codes.
MemberDAO.java
package sec05.ex01;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class MemberDAO {
PreparedStatement pstmt;
Connection connection;
public List<MemberVO> listMembers() {
List<MemberVO> list = new ArrayList<>();
try {
connDB();
String query = "SELECT * FROM t_member";
System.out.println("preparedStatement: " + query);
pstmt = connection.prepareStatement(query);
ResultSet rs = pstmt.executeQuery(query);
while (rs.next()) {
String id = rs.getString("id");
String pwd = rs.getString("pwd");
String name = rs.getString("name");
String email = rs.getString("email");
Date joinDate = rs.getDate("joinDate");
MemberVO vo = new MemberVO();
vo.setId(id);
vo.setPwd(pwd);
vo.setName(name);
vo.setEmail(email);
vo.setJoinDate(joinDate);
list.add(vo);
}
rs.close();
pstmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
private void connDB() {
try {
String url = "jdbc:oracle:thin:#localhost:1521:XE";
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Loaded Oracle Driver");
connection = DriverManager.getConnection(url, "system", "oracle");
System.out.println("Connection created.");
System.out.println("PreparedStatement created.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
MemberServlet.java
package sec05.ex01;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.List;
#WebServlet("/member")
public class MemberServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
MemberDAO dao = new MemberDAO();
List<MemberVO> list = dao.listMembers();
out.print("<html><body>");
out.print("<table border=1><tr align='center' bgcolor='lightgreen'>");
out.print("<td>ID</td><td>PWD</td><td>NAME</td><td>EMAIL</td><td>DATE</td></tr>");
for (MemberVO memberVO : list) {
String id = memberVO.getId();
String pwd = memberVO.getPwd();
String name = memberVO.getName();
String email = memberVO.getEmail();
Date joinDate = memberVO.getJoinDate();
out.print("<tr><td" + id + "</td><td>" + pwd + "</td><td>" + name + "</td><td>" + email + "</td><td>" + joinDate + "</td></tr>");
}
out.print("</table></body></html>");
}
}
MemberVO.java
package sec05.ex01;
import java.sql.Date;
public class MemberVO {
private String id;
private String pwd;
private String name;
private String email;
private Date joinDate;
public MemberVO() {
System.out.println("MemberVO constructor called.");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
}
Error Message
But when I use console in IntelliJ, it works.
Database console in IntelliJ
Also, I added a jdbc library. (I'm using jdk17)
IntelliJ Library
I tried to change the library version to 8.
The ClassNotFoundException and NullPointerException occured.

Retrieve results JAX-RS + Jersey + Jackson

I have this entity class
#Entity
#XmlRootElement
#Table(name="user")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_user", unique=true, nullable=false)
private String idUser;
#Column(nullable=false, length=50)
private String docnum;
#Column(nullable=false, length=50)
private String email;
#Column(nullable=false, length=50)
private String firstname;
#Column(nullable=false, length=50)
private String lastname;
#Column(nullable=false, length=45)
private String pwd;
//bi-directional many-to-many association to Transaction
#ManyToMany
#JoinTable(
name="transaction_users"
, joinColumns={
#JoinColumn(name="user", nullable=false)
}
, inverseJoinColumns={
#JoinColumn(name="transaction", nullable=false)
}
)
private List<Transaction> transactions;
public User() {
}
public String getIdUser() {
return this.idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getDocnum() {
return this.docnum;
}
public void setDocnum(String docnum) {
this.docnum = docnum;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public List<Transaction> getTransactions() {
return this.transactions;
}
public void setTransactions(List<Transaction> transactions) {
this.transactions = transactions;
}
}
generated from a database table. Then i have this rest service
#Path("service/2.0")
public class ServiceTest {
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_JSON)
public Response getUser() {
EntityManager entityManager = EntityManagerUtil.getEntityManager();
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("SELECT u FROM User u");
#SuppressWarnings("unchecked")
List<User> listOfUser = q.getResultList();
System.out.print(listOfUser);
return Response.ok(listOfUser).build();
}
I'm (supposed) to be using the jackson API to handle json but i'm not using maven. For this reason, i've added in my buildpath the following .jars:
jackson-annotations-2.9.3.jar
jackson-core-2.9.3.jar
jackson-databind-2.9.3.jar
jackson-jaxrs-base-2.9.3.jar
jackson-module-jaxb-annotations-2.9.3.jar
jersey-media-json-jackson-2.26.jar
jackson-jaxrs-json-provider-2.9.3.jar
Then i have an ApplicationConfig.java class
package prova;
import com.fasterxml.jackson.jaxrs.json.*;
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
#ApplicationPath("rest")
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
packages("com.fasterxml.jackson.jaxrs.json");
packages("prova");
}
}
When i try to submit a GET request with postman, i obtain an "HTTP 500 internal server error" with the description:
"The server encountered an unexpected condition that prevented it from fulfilling the request."
While from the eclipse console i can see
[EL Fine]: sql: 2017-12-16 17:44:54.251--ServerSession(1869059368)--
Connection(771012214)--Thread(Thread[http-nio-8080-exec-80,5,main])--
SELECT id_user, DOCNUM, EMAIL, FIRSTNAME, LASTNAME, PWD FROM user
[prova.User#3c713cb0, prova.User#49e51730, prova.User#d9ecdd7,
prova.User#383fe468]dic 16, 2017 5:44:54
PM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWr
iterInterceptor aroundWriteTo
GRAVE: MessageBodyWriter not found for media type=application/json,
type=class java.util.Vector, genericType=class java.util.Vector.
So what i can deduce is that the query is correctly executed and it returns an array of 4 object (prova is the name of my entity manager) but then i have the GRAVE:MessageBodyWriter Error
What the hell i'm not doing correctly?why i can not retrieve my JSON data?
Thanks
UPDATE
Following the advice, i've modified the GET resource into
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String getUser() {
return String.valueOf(10+4);
}
and submitting the GET request gives me the expected JSON answer from Postman "14"....
Can the problem be the conversion of a List into Json?if yes, what to do?
Thanks
UPDATE 2
I've edited the code of the REST resource in this way:
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String getUser() {
EntityManager entityManager = EntityManagerUtil.getEntityManager();
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("SELECT u FROM User u");
List<User> listOfUser = q.getResultList();
System.out.print(listOfUser);
if (listOfUser.isEmpty()) {
System.out.println("VOID LIST");
entityManager.close();
return String.valueOf(2);
}
for (User user : listOfUser) {
System.out.println(user.getFirstname());
System.out.println("---");
}
return String.valueOf(3);
}
The postman Output is "3" so, everything fine while the consoloe output is:
[EL Fine]: sql: 2017-12-17 13:48:33.214--ServerSession(286337061)--
Connection(2132504260)--Thread(Thread[http-nio-8080-exec-2,5,main])--
SELECT id_user, DOCNUM, EMAIL, FIRSTNAME, LASTNAME, PWD FROM USER
[prova.User#2d3017ff, prova.User#6361d00, prova.User#7ab0944a,
prova.User#5945162f]
matteo
---
tony
---
bruce
---
peter
---
which is perfectly consistent with what i have in the table of the DB... :(
Try to convert your response entity in an array of users. There is proper equivalent for array in json.
Other way ist to have a wrapper class for your list of users.
#XmlType
#XmlRootElement
class Wrapper {
#XmlElement
List<User> users;
}
Return this in your response.

Getting class cast exception when doing a POST request using JAX-RS with hibernate backend

I have a simple User POJO class, its definition is as follows:
package models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement
#Table(name="USER",uniqueConstraints={#UniqueConstraint(columnNames="email")})
public class User {
#XmlElement
private String name;
#Id
#XmlElement
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#XmlElement
private String email;
#XmlElement
private int age;
#Override
public String toString() {
return "User [name=" + name + ", id=" + id + ", email=" + email + ", age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
and my resource mapping is as follows:
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/Person")
public Response insertPerson(User user) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
int uid = (Integer)session.save(user);
tx.commit();
session.close();
return Response.status(201).entity(uid).build();
}
When i do a post request using PostMan i am getting this exception on server:
Dec 20, 2015 9:44:42 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/expenseManagement] threw exception [Exception [EclipseLink-6065] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.QueryException
Exception Description: Cannot add the object [User [name=manjunath, id=100, email=manjunath#gmail.com, age=15]], of class [class models.User], to container [class models.User].
Internal Exception: java.lang.ClassCastException: models.User cannot be cast to java.util.Collection] with root cause
java.lang.ClassCastException: models.User cannot be cast to java.util.Collection
I have provided message body readers as well, I don't know where i am going wrong, can someone please help.
The content you send is surrounded by [ and ] marking it an array, not an object. Try sending only this String:
{"name":"manjunath", "age":15, "id":100, "email":"manjunath#gmail.com"}
Good Luck

Error in hibernate call using annotations

I am getting this error
menu_categories is not mapped [from menu_categories]
my hibernate call is
public List loadMenuCategories(SessionFactory sessionFactory){
List types = new ArrayList<MenuCategories>();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from menu_categories");
List result = query.list();
Iterator it = result.iterator();
while(it.hasNext()){
MenuCategories menuCategories = (MenuCategories)it.next();
types.add(menuCategories);
}
sessionFactory.close();
return types;
}
and my bean is
#Entity
#Table(appliesTo = "menu_categories")
public class MenuCategories extends BaseModel{
/**
*
*/
private static final long serialVersionUID = -4875305890823765933L;
}
package com.rizstien.myhotel.framework.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.apache.commons.lang.StringUtils;
public class BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable=false)
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String desc;
#Column(name = "is_active")
private boolean active;
#Column(name = "no_of_items")
private Integer noOfItems;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
if (!StringUtils.isEmpty(name)) {
this.name = name;
}
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
if (!StringUtils.isEmpty(desc)) {
this.desc = desc;
}
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Integer getNoOfItems() {
return noOfItems;
}
public void setNoOfItems(Integer noOfItems) {
this.noOfItems = noOfItems;
}
}
EDIT
this is my hibernate config file
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3311/myhotel</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">5</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.rizstien.myhotel.menucategories.model.MenuCategories"/>
</session-factory>
The query you're executing is not SQL. It's HQL. HQL queries entities, not tables. It should thus be from MenuCategories. This entity, BTW, should be named MenuCategory, sicne one instance of it represent one category, and not several categories.
Read the documentation.
I had mentioned db name in annotation and it solved the problem
#Entity
#Table(name = "menu_categories", catalog="db_name")
public class MenuCategories extends BaseModel{
private static final long serialVersionUID = -4875305890823765933L;
}

Can't get Form Validation working

I was learning Struts 1.1 and trying to do some form validation with my code.
But the errors that I had described in the MessageResources.properties file do not get displayed on the JSP. I tried a lot of options but couldn't get it off the ground. I have attached some of the code.
MessageResources.properties
error.name.required = Please mention your name.
error.email.incorrect = You E-Mail ID is Incorrect.
error.phone.numericError = Phone number should consist only of digits.
error.phone.lengthIncorrect = Phone number should be only of 10 digits.
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans>
<form-bean name="detailsForm" type="com.example.form.DetailsForm"/>
</form-beans>
<action-mappings>
<action input="/detailsEntry.jsp" name="detailsForm" path="/DetailsForm" type="com.example.action.DetailsAction" validate="true">
<forward name="success" path="/displayDetails.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
</action-mappings>
</struts-config>
Form Class:
package com.example.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
public class DetailsForm extends ActionForm {
private String name;
private String email;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.name = null;
this.email = null;
this.phone = null;
}
#Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors actionErrors = new ActionErrors();
if (this.name.equals(null) || this.name.length() == 0) {
actionErrors.add("name", new ActionError("error.name.required"));
}
return actionErrors;
}
private boolean isNumeric(String phoneNumber) {
try {
Integer.parseInt(phoneNumber);
return true;
}
catch (NumberFormatException numberFormatException) {
return false;
}
}
}
The default resource filename is ApplicationResources.properties.
Using a different (or multiple) resource files requires configuration in struts-config.xml:
<message-resource parameter="MessageResources" null="false" />
Don't forget to add the following to your jsp:
<html:errors />
Your error messages will appear where ever you put this tag on on your jsp.
And if you want your error message to be displayed next to the field they relates to then use the following:
<html:errors property="custName" />
where "custName" is the name you gave the error message when you created it in your form ex:
ActionMessages errors = new ActionMessages();
errors.add("custName", new ActionMessage("custName.invalid"));
request.setAttribute(Globals.ERROR_KEY, errors);