Values from the database is not being displayed in Dynamic report - java

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);

Related

org.hibernate.MappingException: Unknown entity: com.tss.friends_api.user.model.User

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 .

new Configuration().configure().buildSessionFactory() is creating new connection on each call

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

Exception in thread "main" org.hibernate.MappingException

Test:
import java.util.GregorianCalendar;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import it.s.monitoringDoor.model.Door_Open;
import it.s.monitoringDoor.model.HibernateUtilities;
public class TestHibernate {
public static void main(String[] args){
SessionFactory factory = HibernateUtilities.getSessionFactory();
Door_Open d = new Door_Open();
d.setId(1);
d.setId_door(1);;
d.setTimestamp(getTime());
Session s = factory.openSession();
Transaction t = s.getTransaction();
t.begin();
s.save(d);
t.commit();
}
private static Date getTime(){
GregorianCalendar gc = new GregorianCalendar();
return gc.getTime();
}
}
HibernateUtilities:
package it.s.monitoringDoor.model;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtilities {
//XML based configuration
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
The Pojo class Door_Open.java
package it.selco.monitoringDoor.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "door_open")
public class Door_Open {
//---------------- Instance variables ----------------
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "id_door", nullable = false)
private int id_door;
#Column(name = "id_door", nullable = false)
private Date timestamp;
//-------------------- Constructor --------------------
public Door_Open (){
;
}
public Door_Open(int id_door, Date timestamp) {
setId_door(id_door);
setTimestamp(timestamp);
}
//--------------------- Get & Set ---------------------
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#SuppressWarnings("unused")
private int getId_door() {
return id_door;
}
public void setId_door(int id_door) {
this.id_door = id_door;
}
#SuppressWarnings("unused")
private Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
//--------------------- Methods ----------------------
//TODO Auto-generated methods variables block
}
hibernate.cfg.xml
<?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 name="">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/monitor_door</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- ############################################
# mapping files with external dependencies #
############################################ -->
<mapping resource="it/s/monitoringDoor/model/Door_Open.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Door_Open.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Door_Open" table="door_open" schema="monitor_door">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="id_door" column="id_door" type="int" not-null="true"/>
<property name="timestamp" column="timestamp" type="timestamp" not-null="true"/>
</class>
</hibernate-mapping>
When I run the test is returned me the following error.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: it.s.monitoringDoor.model.Door_Open
[...]
some advice?
Look at the package of your Door_Open class, it is: it.selco.monitoringDoor.model while in hibernate.cfg.xml the Door_Open.hbm.xml file is at: <mapping resource="it/s/monitoringDoor/model/Door_Open.hbm.xml"/>. The package and the mapping resource path do not match, they should be the same e.g. it/selco/monitoringDoor/model/Door_Open.hbm.xml
and of course move the Door_Open.hbm.xml to be in the same path as its class.
Hope this helps.
PS, why are you using both annotations (e.g. #Entity) and hbm mapping for your class? I think you should choose one not both.

Spring + TestNG not transactionally rollback

I'm using TestNG 6.9.9 to build-up a regression test environment. But encounter a problem which I have never met when using JUnit.
In my mind, when finish each test cases, the change of each data would be automatically rollback by default if the test methods run in the same transaction context as what they call. But seems that it's not the truth, and I cannot find out if any mistake in my code. Please help me out.
properties in pom.xml which indicates the frameworks' version
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>4.2.4.RELEASE</springframework.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<testng.version>6.9.9</testng.version>
</properties>
Obviously, they are all up-to-date.
My test class:
package com.noahwm.hkapp.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
import com.noahwm.hkapp.api.service.AppUserService;
#ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public class AppUserServiceTestNGTest extends AbstractTestNGSpringContextTests {
#Autowired
private AppUserService appUserService;
#Test
#Rollback
#Transactional
public void testApp() {
AppUser appUser = new AppUser();
appUser.setAge(10);
appUser.setGender("F");
appUser.setMobilePhone("13219201034");
appUser.setName("HKAPP Test");
appUserService.createUser(appUser);
String appUserId = appUser.getId();
Assert.assertNotNull(appUserId);
}
}
Created a entity instance, than call createUser() to save it to DB. According what I have done in JUnit, the data will automatically rollback even if I didn't put the #Rollback annotation in the front of the test method.
The structure of AppUser is:
package com.noahwm.hkapp.api.db.model;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity(name = "APP_USERS")
public class AppUser extends BaseDataModel {
#Column(name = "NAME")
private String name;
#Column(name = "GENDER")
private String gender;
#Column(name = "AGE")
private Integer age;
#Column(name = "MOBILE_PHONE")
private String mobilePhone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
}
BaseDataModel.java
package com.noahwm.hkapp.api.db.model;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import org.hibernate.annotations.GenericGenerator;
#MappedSuperclass
public class BaseDataModel {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
#Column(name = "ID", unique = true, length = 36, nullable = false)
protected String id;
#Version
#Column(name = "version")
protected Integer version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
}
ApplicationContext-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.test.properties</value>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="com.noahwm.hkapp.api" />
<aop:aspectj-autoproxy />
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"
lazy-init="true" />
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxConnectionsPerPartition" value="${jdbc.maxConnectionsPerPartition}" />
<property name="minConnectionsPerPartition" value="${jdbc.minConnectionsPerPartition}" />
<property name="partitionCount" value="${jdbc.partitionCount}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.noahwm.hkapp.api.db.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.jdbc.fetch_size">30</prop>
<prop key="hibernate.default_batch_fetch_size">10</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"
proxy-target-class="true" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
The transaction-manager is named “txManager”.
AppUserService.java
package com.noahwm.hkapp.api.service;
import java.util.List;
import java.util.Map;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
public interface AppUserService {
void createUser(AppUser user);
}
AppUserServiceImpl.java
package com.noahwm.hkapp.api.service.impl;
import java.util.List;
import java.util.Map;
import org.hibernate.criterion.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
import com.noahwm.hkapp.api.service.AppUserService;
import com.noahwm.hkapp.api.service.EntityService;
import com.noahwm.hkapp.utils.SimpleSearchCriteria;
#Service("AppUserService")
#Transactional(propagation=Propagation.REQUIRED)
public class AppUserServiceImpl extends EntityService implements AppUserService {
private static final Logger logger = LoggerFactory.getLogger(AppUserServiceImpl.class);
#Autowired
private AppUserDao dao;
#Override
public void createUser(AppUser user) {
logger.debug("Creating user with name {}", user.getName());
dao.save(user);
}
}
AppUserDao.java
package com.noahwm.hkapp.api.db.dao;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.noahwm.hkapp.api.db.model.AppUser;
#Repository
#Transactional(propagation=Propagation.REQUIRED)
public class AppUserDao extends BaseDao<AppUser> {
public void testsRollBack(AppUser appUser) throws Exception{
save(appUser);
}
}
BaseDao.java
package com.noahwm.hkapp.api.db.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import com.noahwm.hkapp.api.db.model.BaseDataModel;
import com.noahwm.hkapp.utils.SimpleSearchCriteria;
class BaseDao<T extends BaseDataModel> {
private Class<T> domainClass;
#Resource(name = "sessionFactory")
protected SessionFactory sessionFactory;
protected SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public Class<T> getDomainClass() {
if (domainClass == null) {
Type type = this.getClass().getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) type;
domainClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
return domainClass;
}
protected Session getCurrentSession() {
return getSessionFactory().getCurrentSession();
}
public Criteria createCriteria() {
return getCurrentSession().createCriteria(getDomainClass());
}
public void save(T o) {
getCurrentSession().save(o);
}
public void update(T o) {
getCurrentSession().update(o);
}
public void saveOrUpdate(T o) {
getCurrentSession().saveOrUpdate(o);
}
public Object merge(Object o) {
return getCurrentSession().merge(o);
}
public void delete(T o) {
getCurrentSession().delete(o);
}
public T deleteById(Serializable id) {
T o = findById(id);
getCurrentSession().delete(o);
return o;
}
public void evict(Object o) {
getCurrentSession().evict(o);
}
#SuppressWarnings("unchecked")
public List<T> findAll() {
return createCriteria().list();
}
#SuppressWarnings("unchecked")
public T findById(Serializable o) {
List<T> results = createCriteria().add(Restrictions.idEq(o)).list();
if (results.isEmpty()) {
return null;
} else {
return results.get(0);
}
}
#SuppressWarnings("unchecked")
public T load(Serializable o) {
return (T) getCurrentSession().load(getDomainClass(), o);
}
#SuppressWarnings("unchecked")
public List<T> findBy(Map<String, Object> propertyNameValues) {
return createCriteria().add(Restrictions.allEq(propertyNameValues)).list();
}
#SuppressWarnings("unchecked")
public List<T> findBy(String propertyName, Object value) {
return createCriteria().add(Restrictions.eq(propertyName, value)).list();
}
#SuppressWarnings("unchecked")
public List<T> find(SimpleSearchCriteria simpleSearchCriteria) {
Criteria criteria = createCriteria();
Iterator<Criterion> criterions = simpleSearchCriteria.iterator();
while(criterions.hasNext()) {
criteria.add(criterions.next());
}
for(Order o : simpleSearchCriteria.getOrders()) {
criteria.addOrder(o);
}
if(simpleSearchCriteria.getFetchSize() != null) {
criteria.setFetchSize(simpleSearchCriteria.getFetchSize());
}
if(simpleSearchCriteria.getFirstResult() != null) {
criteria.setFirstResult(simpleSearchCriteria.getFirstResult());
}
if(simpleSearchCriteria.getMaxResults() != null) {
criteria.setMaxResults(simpleSearchCriteria.getMaxResults());
}
if(simpleSearchCriteria.getTimeout() != null) {
criteria.setTimeout(simpleSearchCriteria.getTimeout());
}
return criteria.list();
}
public T findFirst(SimpleSearchCriteria simpleSearchCriteria) {
simpleSearchCriteria.setMaxResults(1);
List<T> results = find(simpleSearchCriteria);
if(results.isEmpty()) {
return null;
} else {
return results.get(0);
}
}
public Object callNamedQuery(String sql, Map<String, Object> parameter) {
Query query = getCurrentSession().createSQLQuery(sql);
for(Entry<String, Object> entry:parameter.entrySet()){
query.setParameter(entry.getKey(), entry.getValue());
}
return query.executeUpdate();
}
}
Here is the DB init script:
CREATE TABLE "APP_USERS" (
"ID" VARCHAR(36),
"NAME" VARCHAR(50),
"GENDER" VARCHAR(1),
"AGE" NUMERIC(3,0),
"MOBILE_PHONE" VARCHAR(20),
VERSION INTEGER)
As you see, it's a very common Spring TestNG integration test. But the auto rollback function cannot be used which bordered me a lot.
Thanks to M. Deinum.
To solve my problem, I just replace the class AbstractTestNGSpringContextTests with AbstractTransactionalTestNGSpringContextTests.
package com.noahwm.hkapp.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
import com.noahwm.hkapp.api.service.AppUserService;
#ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public class AppUserServiceTestNGTest extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private AppUserService appUserService;
#Test
#Rollback
#Transactional
public void testApp() {
AppUser appUser = new AppUser();
appUser.setAge(10);
appUser.setGender("F");
appUser.setMobilePhone("13219201034");
appUser.setName("HKAPP Test");
appUserService.createUser(appUser);
String appUserId = appUser.getId();
Assert.assertNotNull(appUserId);
}
}

How to give foreign key in Hibernate

This is My LOGIN1.java class
import java.io.Serializable;
public class LOGIN1 implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String Email;
private String Password;
private Registration registration;
public Registration getRegistration() {
return registration;
}
public void setRegistration(Registration registration) {
this.registration = registration;
}
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
This Is My Registration.java
import java.io.Serializable;
public class Registration implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String contact;
private String Name;
private String amount;
private LOGIN1 login1;
public LOGIN1 getLogin1() {
return login1;
}
public void setLogin1(LOGIN1 login1) {
this.login1 = login1;
}
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
This Is My LOGIN1.hbm.xml
<?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="LOGIN1" table="LOGIN1">
<id name="id" column="id" type="integer">
<generator class="increment"/>
</id>
<property name="Email" column="EMAIL" type="string"></property>
<property name="Password" column="Password" type="string"></property>
<one-to-one name="registration" class="Registration" cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
this is my Registration.hbm.xml
<id name="id" column="id" type="integer">
<generator class="foreign">
<param name="property">rg</param>
</generator>
</id>
<one-to-one name="login1" class="LOGIN1" constrained="true"></one-to-one>
<property name="Name" column="Name" type="string"></property>
<property name="contact" column="contct" type="string"></property>
<property name="amount" column="iamt" type="string"></property>
</class>
</hibernate-mapping>
This is my hibernate.cfg
<?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.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=HiberNate</property>
<property name="hibernate.connection.username">aaa</property>
<property name="hibernate.connection.password">aaa</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="show_sql">true</property>
<mapping resource="LOGIN1.hbm.xml"></mapping>
<mapping resource="Registration.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
This is My Hiberservlets
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 org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
#WebServlet("/HiberServlet")
public class HiberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HiberServlet() {
}
#SuppressWarnings("deprecation")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
out.print("Hello");
String a,b,c,d,e;
a=request.getParameter("cnm");
b=request.getParameter("cntno");
c=request.getParameter("amt");
d=request.getParameter("eml");
e=request.getParameter("pwd");
Session s=HibernateUtil.openSession();
Transaction tx = s.beginTransaction();
try {
LOGIN1 ln=new LOGIN1();
ln.setEmail(d);
ln.setPassword(e);
s.save(ln);
Criteria cr=s.createCriteria(LOGIN1.class);
cr.add(Restrictions.eq("Email",d));
cr.add(Restrictions.eq("Password",e));
int i=ln.getId();
Registration rg=new Registration();
rg.setId(i);
rg.setName(a);
rg.setContact(b);
rg.setAmount(c);
s.save(rg);
tx.commit();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
if(s!=null)
{
s.flush();
s.close();
}
}
catch(HibernateException e)
{
System.out.print(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
i am trying This but its Give error like
java.lang.NullPointerException
org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:650)
org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4736)
org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:96)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
HiberServlet.doGet(HiberServlet.java:77)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
And i am Using eclipse.what is problem in this code.
This
org.hibernate.PropertyNotFoundException: field [LOGIN1] not found on Registration
indicates, that your mapping does not match your class. There is probably no LOGIN1 property in the class. If it exists at all it is probably called login1 in lower case letters

Categories