HTTP 400 on hitting Restful post service defined using Spring 4 MVC and MappingJackson2HttpMessageConverter - spring

I'm trying to create a restful controller using Spring 4 MVC and testing it with Fiddler by hitting the below mentioned RestFul Post web service but getting HTTP/1.1 400 Bad Request as response, after i have added MappingJackson2HttpMessageConverter to my dispatcher-servlet.xml. The Response comes up correctly If i use '#RequestBody String resource' instead of '#RequestBody Resource resource' for ResourceController post method arguments. I've added MappingJackson2HttpMessageConverter to dispatcher-servlet.xml since spring was not detecting jackson and was throwing HTTP 415 on hitting this post service.
URL : http://localhost:8080/rma/api/resources/1
Headers :
User-Agent: Fiddler
Host: localhost:8080
Content-Length: 171
Accept: application/json
Content-Type: application/json
Request Body :
{
"firstName" : "first",
"middleName" : "middle",
"lastName" : "last",
"email": "first#last.com",
"dateOfBirth": "09-10-1988",
"titleRole" : "software engineer"
}
dispatcher-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.pkg.controller" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<bean id="resourceDao" class="com.pkg.dao.ResourceDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost/rma?"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
ResourceController.class
#RestController
#RequestMapping("/resources")
public class ResourceController {
#Autowired
private final ResourceDao resourceDao;
#Autowired
public ResourceController(ResourceDao resourceDao) {
this.resourceDao = resourceDao;
}
//get resources for a resource id
#RequestMapping(value ="/{hiringManager}", method = RequestMethod.GET, produces="application/json")
public List<Resource> getResources(#PathVariable String hiringManager){
return resourceDao.getResources(hiringManager);
}
//post a new resource for a resource id
#RequestMapping(value ="/{hiringManager}",method = RequestMethod.POST, consumes="application/json",produces="application/json")
public ResponseEntity<Resource> addResources(#PathVariable String hiringManager, #RequestBody Resource resource){
System.out.println("In controller" + hiringManager + " > Adding " +resource.toString());
return new ResponseEntity<Resource>(resource,HttpStatus.CREATED);
}
}
WebApplicationInitializer.class
public class ApplicationInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
//Registering Dispatcher Servlet
try{
ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet());
registration.setLoadOnStartup(1);
registration.addMapping("/api/*"); // URL mapping
} catch(Exception e){
e.printStackTrace();
}
}
}
Resource.class
#Entity
public class Resource{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String firstName;
private String middleName;
private String lastName;
private String email;
#Temporal(TemporalType.DATE)
private Date dateOfBirth;
private String titleRole;
private String hiringManagerId;
public Resource(){
}
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 Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getTitleRole() {
return titleRole;
}
public void setTitleRole(String titleRole) {
this.titleRole = titleRole;
}
public String getHiringManagerId() {
return hiringManagerId;
}
public void setHiringManagerId(String hiringManagerId) {
this.hiringManagerId = hiringManagerId;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>rma</groupId>
<artifactId>rma</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- Spring Core Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.1</version>
</dependency>
<!-- Logger Dependency -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<!-- Unit Testing Dependency -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Connection Pooling Dependency -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.3</version>
</dependency>
<!-- ORM Dependency -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- Database Dependency -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

Related

Parse csv file by using Spring Batch and print it on console in spring Boot

My goal of the Project :
I have to read csv file by using Spring Batch and extract the specific column information like (Column Name :"msdin") "msdin" can print it on console. But my application is showing failed to start the application.
Well it is asking me to configure the data Source.Why we need to configure the data source in case of spring batch if my requirement is to read the csv file and print it on console.
I tried to identify the issues but not able to resolve. Can anybody help me how to resolve this issues?
Domain Class
public class Customer implements Serializable {
private Long id_type;
private String id_number;
private String customer_name;
private String email_address;
private LocalDate birthday;
private String citizenship;
private String address;
private Long msisdn;
private LocalDate kyc_date;
private String kyc_level;
private String goalscore;
private String mobile_network;
public Long getId_type() {
return id_type;
}
public void setId_type(Long id_type) {
this.id_type = id_type;
}
public String getId_number() {
return id_number;
}
public void setId_number(String id_number) {
this.id_number = id_number;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getEmail_address() {
return email_address;
}
public void setEmail_address(String email_address) {
this.email_address = email_address;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getMsisdn() {
return msisdn;
}
public void setMsisdn(Long msisdn) {
this.msisdn = msisdn;
}
public LocalDate getKyc_date() {
return kyc_date;
}
public void setKyc_date(LocalDate kyc_date) {
this.kyc_date = kyc_date;
}
public String getKyc_level() {
return kyc_level;
}
public void setKyc_level(String kyc_level) {
this.kyc_level = kyc_level;
}
public String getGoalscore() {
return goalscore;
}
public void setGoalscore(String goalscore) {
this.goalscore = goalscore;
}
public String getMobile_network() {
return mobile_network;
}
public void setMobile_network(String mobile_network) {
this.mobile_network = mobile_network;
}
}
BatchConfiguration class
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Value("classPath:/data/gcash.csv")
private Resource inputResource;
public ItemReader<Customer> itemReader() {
FlatFileItemReader<Customer> customerItemReader = new FlatFileItemReader<>();
customerItemReader.setLineMapper(linemapper());
customerItemReader.setLinesToSkip(1);
customerItemReader.setResource(inputResource);
return customerItemReader;
}
#Bean
public LineMapper<Customer> linemapper() {
DefaultLineMapper<Customer> linemapper = new DefaultLineMapper<>();
final DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setDelimiter(";");
tokenizer.setStrict(false);
tokenizer.setNames(new String[] { "id_type", "id_number", "customer_name", "email_address", "birthday",
"citizenship", "address", "msisdn", "kyc_date", "kyc_level", "goalscore", "mobile_network" });
linemapper.setFieldSetMapper(new BeanWrapperFieldSetMapper<Customer>() {
{
setTargetType(Customer.class);
}
});
return linemapper;
}
}
Error Stack
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-04-27 11:05:46.235 ERROR 22368 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.gcash.milo</groupId>
<artifactId>GCash_Milo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GCash_Milo</name>
<description>Developing Milo project for GCash banking application.
</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-sftp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
in your spring boot application class, add the following snippet to #SpringBootApplication annotation:
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
#SpringBootApplcation annotation uses #EnableAutoConfiguration, which expects a datasource to be configured

I'm getting an exception in javax.persistance when trying to connect my entity class to mySQL using JPA. How do I fix it?

I'm trying to create a simple user entity class and add the tables to the mysql database but I'm getting the following error when I run the class.
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named default
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:84)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at com.all.Controller.main(Controller.java:12)
This points to this line :
EntityManagerFactory entityManagerFactory= Persistence.createEntityManagerFactory("default");
package com.all;
import com.some.User;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Controller {
public static void main(String[]args){
EntityManagerFactory entityManagerFactory= Persistence.createEntityManagerFactory("default");
EntityManager entityManager= entityManagerFactory.createEntityManager();
User user= new User();
user.setName("rizana");
user.setSalary(6000);
entityManager.getTransaction().begin();
entityManager.persist(user);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
}
}
package com.some;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue
private int num;
private String name;
private double salary;
private String id;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return "User{" +
"num=" + num +
", name='" + name + '\'' +
", salary=" + salary +
", id='" + id + '\'' +
'}';
}
}
persistence.xml file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<class>com.some.User</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/users"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.jdbc.schema-generation.database.action" value="create"/>
<!-- <property name="eclipselink.logging.level" value="SEVERE"/>
<property name="eclipselink.ddl-generation" value="create"/>-->
</properties>
</persistence-unit>
</persistence>
I manually added the eclipselink dependencies to the pom.xml file. I'm using Intellij IDE
POM.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>1.0-SNAPSHOT</version>
<name>demo1</name>
<repositories>
<repository>
<id>eclipselink</id>
<url>http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo/</url>
</repository>
</repositories>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.6.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
</plugins>
</build>
</project>

why i am getting nullpointerexception in JSP page for Spring DAO methods?

here, whenever I trying to access or call the DAO method (which is written in #Repository class) in the JSP page in My spring MVC Project using Hibernate, it showing NullPointerException.
it works fine when I accessing this method in Controller class, it just throwing an exception in the JSP page.
and here expection i am getting,
SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.NullPointerException
at com.lms.service.BookDetailsServiceImpl.getBookStatusForLibrarianById(BookDetailsServiceImpl.java:62)
here is my code,
in pom.xml,
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.libmansystem</groupId>
<artifactId>LibraryManagementSystems</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>LibraryManagementSystems Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.0.RELEASE</springsecurity.version>
<hibernate.version>5.4.14.Final</hibernate.version>
<mysql.connector.version>8.0.20</mysql.connector.version>
<c3po.version>0.9.5.5</c3po.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Add MySQL and C3P0 support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3po.version}</version>
</dependency>
<!-- Servlet, JSP and JSTL support -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jstl-impl</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>LibraryManagementSystems</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add maven co-ordinates for : maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
entity class,
#Entity
#Table(name = "book_status_forlibrarian")
public class BookStatusForLibrarian {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "s_id")
private Integer id;
#Column(name = "status")
private String status;
public BookStatusForLibrarian() {
}
public BookStatusForLibrarian(Integer id, String status) {
this.id = id;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "BookStatusForLibrarian [id=" + id + ", status=" + status + "]";
}
}
Dao interface and class,
public interface BookDetailsDAO {
public BookStatusForLibrarian getBookStatusForLibrarianById(int statusId);
}
#Repository
public class BookDetailsDAOImpl implements BookDetailsDAO{
private SessionFactory sessionFactory;
#Autowired
public BookDetailsDAOImpl(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public BookDetailsDAOImpl()
{
}
#Override
public BookStatusForLibrarian getBookStatusForLibrarianById(int statusId) {
Session theSession = sessionFactory.getCurrentSession();
BookStatusForLibrarian theBookStatusForLibrarian = theSession.get(BookStatusForLibrarian.class, statusId);
return theBookStatusForLibrarian;
}
}
my service interface and class,
public interface BookDetailsService {
public BookStatusForLibrarian getBookStatusForLibrarianById(int statusId);
}
#Service
public class BookDetailsServiceImpl implements BookDetailsService {
#Autowired
BookDetailsDAO theBookDetailsDAO;
#Override
#Transactional
public BookStatusForLibrarian getBookStatusForLibrarianById(int statusId) {
System.out.println("inside service ");
return theBookDetailsDAO.getBookStatusForLibrarianById(statusId);
}
}
my controller,
#Controller
public class HomePageController {
#GetMapping("/homepage")
public String getHomePage()
{
return "homepage";
}
}
in my JSP page I am getting exception,
/WEB-INF/view/homepage.jsp,
<%#page import="com.lms.service.NonServiceMethod"%>
<%#page import="com.lms.dao.BookDetailsDAOImpl"%>
<%#page import="com.lms.service.BookDetailsServiceImpl"%>
<%#page import="com.lms.service.BookDetailsService"%>
<%#page import="com.lms.entity.BookStatusForLibrarian"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Show All Book</title>
</head>
<body>
<%
System.out.println("getting exception while calling Spring DAO method (which is written in #Repository class) in JSP page");
BookDetailsServiceImpl theBookDetailsService = new BookDetailsServiceImpl();
BookStatusForLibrarian getBookStatus= theBookDetailsService.getBookStatusForLibrarianById(3);
%>
</body>
</html>
and here expection i am getting,
SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.NullPointerException
at com.lms.service.BookDetailsServiceImpl.getBookStatusForLibrarianById(BookDetailsServiceImpl.java:62)
please help me.
If you create the service in the JSP, it is not a Spring bean. There is no dependency injection done by Spring, you DAO is not injected in your service (NullPointerException). The correct way to pass the model (BookStatusForLibrarian) into the view (JSP) is to use the Controller.
#Controller
public class HomePageController {
#Autowired
BookDetailsService bookDetailsService;
#GetMapping("/homepage")
public String getHomePage(Model model) {
BookStatusForLibrarian bookStatus = bookDetailsService.getBookStatusForLibrarianById(3);
model.addAttribute("bookStatus", bookStatus);
return "homepage";
}
}
Then you can use bookStatus directly in the JSP without <% %> just like this: ${bookStatus.id}

Error creating bean with the name localContainerEntityManagerFactorryBean defined in the class path resource hibernateconfig.class

I'm getting the Error creating bean with the name localContainerEntityManagerFactorryBean defined in the class path resource hibernateconfig.class. nested exception is javax.persistence.persistenceException:unable to build hibernate session factory: A foreign key referring organizer from events has the wrong no of column, should be 2.
My pom file is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.EventToday</groupId>
<artifactId>EventToday</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>EventToday</name>
<description>projects for events</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<springframework.version>4.0.6.RELEASE</springframework.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<mysql.version>5.1.31</mysql.version>
<joda-time.version>2.3</joda-time.version>
<testng.version>6.9.4</testng.version>
<mockito.version>1.10.19</mockito.version>
<h2.version>1.4.187</h2.version>
<dbunit.version>2.2</dbunit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>ejb3-persistence</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<!-- jsr303 validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.2.GA</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<!-- Joda-Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- To map JodaTime with database type -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>3.0.0.CR1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>EventToday</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<compilerArgs>
<arg>-Aopenjpa.metamodel=true</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>
and hibernate configuration
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.EventToday.event.repository")
#ComponentScan({ "com.EventToday.event" })
#PropertySource(value = { "classpath:application.properties" })
public class hibernateconfig {
#Autowired
private Environment environment;
#Bean
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.MYSQL);
//vendorAdapter.setGenerateDdl(generateDDL);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean beanFactory = new LocalContainerEntityManagerFactoryBean();
beanFactory.setJpaVendorAdapter(vendorAdapter);
beanFactory.setPackagesToScan("com.EventToday.event.model");
beanFactory.setDataSource(dataSource());
//beanFactory.afterPropertiesSet();
beanFactory.setJpaProperties(hibernateProperties());
return beanFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("spring.datasource.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
dataSource.setSchema(environment.getRequiredProperty("spring.datasource.schema"));
dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("spring.jpa.properties.hibernate.dialect", environment.getRequiredProperty("spring.jpa.properties.hibernate.dialect"));
properties.put("spring.jpa.show_sql", environment.getRequiredProperty("spring.jpa.show-sql"));
properties.put("spring.jpa.properties.hibernate.format_sql", environment.getRequiredProperty("spring.jpa.properties.hibernate.format_sql"));
return properties;
}
#Bean
public EntityManagerFactory entityManagerFactory(){
return localContainerEntityManagerFactoryBean().getObject();
}
#Bean
public EntityManager entityManager(){
return entityManagerFactory().createEntityManager();
}
#Bean
PlatformTransactionManager transactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory());
return manager;
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
}
organizer
#Entity
#Table(name="organizer")
public class Organizer extends BaseEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int roid;
#Column(name="orgNname", nullable=false)
private String organizerName;
#Column(name = "org_contact", nullable = false)
private String orgTelephone;
#Column(name = "org_altcontact", nullable = false)
private String orgContact;
#Column(name = "org_mail_address", nullable = false)
private String mailAddress;
#Column(name = "org_address", nullable = false)
private String orgAddress;
#OneToMany(mappedBy = "organizer")
private Set<events> evts;
public Set<events> getEvts() {
return evts;
}
public void setEvts(Set<events> evts) {
this.evts = evts;
}
public Organizer() {
}
//getters and setters
}
#events
#Entity
#Table(name="event")
public class events extends BaseEntity{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#ManyToOne
#JoinColumn(name = "roid")
private Organizer organizer;
public events() {
}
#Column(name = "event_name", nullable = false)
private String eventname;
#Column(name = "event_date", nullable = false)
#DateTimeFormat(pattern="dd/MM/yyyy")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate date;
#NotNull
#Digits(integer=8, fraction=2)
#Column(name = "ticket_price", nullable = false)
private BigDecimal price;
#Column(name="event_location", nullable=false)
private String location;
#Column(name="happening_city", nullable=false)
private String Address;
#Column(name="contact_no", nullable=false)
private String contact_no;
#Column(name="alt_contact_no", nullable=false)
private String alternate_contact;
#Column(name="mail_address")
private String mail_address;
//getters and setters
}

The object doesn't get persisted in Hibernate 4

I configured Hibernate and Spring.
The config and Java class:
package com.dao.impl;
import com.dao.IPersonRepository;
import com.dao.impl.generic.GenericRepository;
import com.model.Person;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ramezanimatin on 8/18/2015.
*/
#Repository
public class PersonRepository extends GenericRepository<Person, Long> implements IPersonRepository {
}
package com.dao;
import com.dao.iGeneric.IGenericRepository;
import com.model.Person;
/**
* Created by ramezanimatin on 8/18/2015.
*/
public interface IPersonRepository extends IGenericRepository<Person, Long> {
}
package com.dao.iGeneric;
import java.io.Serializable;
/**
* Created by ramezanimatin on 8/23/2015.
*/
public abstract interface IGenericRepository<T, pk extends Serializable> {
public void save(T t);
public T loadByEntityId(pk id);
}
package com.dao.impl.generic;
import com.dao.iGeneric.IGenericRepository;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
/**
* Created by ramezanimatin on 8/23/2015.
*/
#Repository
public class GenericRepository<T, pk extends Serializable> implements IGenericRepository<T, pk> {
#Autowired(required = true)
private SessionFactory sessionFactory;
private Session getSession() {
try {
return sessionFactory.getCurrentSession();
} catch (Exception e) {
return sessionFactory.openSession();
}
}
#Override
public void save(Object o) {
getSession().save(o);
}
#Override
public T loadByEntityId(pk id) {
Session session = getSession();
Query query = session.createQuery("from Person e where e.id=:id");
query.setParameter("id", id);
return ((T) query.uniqueResult());
}
}
xml config:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<context:property-placeholder location="classpath:oracle-hibernate.properties"/>
<context:component-scan base-package="com"/>
<!-- <jee:jndi-lookup id="dataSource" jndi-name="test" />-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql"> ${hibernate.show_sql}</prop>
<prop key="hibernate.default_schema"> ${hibernate.default_schema}</prop>
<prop key="hibernate.connection.defaultNChar">true</prop> <!--Oracle need -->
<prop key="hibernate.connection.characterEncoding">UTF8</prop> <!--Oracle need -->
<prop key="hibernate.connection.charSet">UTF8</prop> <!--Oracle need -->
<prop key="hibernate.connection.useEncoding">true</prop> <!--Oracle need -->
<prop key="hibernate.transaction.factory_class" >${hibernate.transaction.factory_class}</prop>
<!-- <prop key="hibernate.transaction.manager_lookup_class" >${hibernate.transaction.manager_lookup_class}</prop>
<prop key="hibernate.current_session_context_class" >${hibernate.current_session_context_class}</prop>-->
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
personService:
package com.service.impl;
import com.dao.IPersonRepository;
import com.model.Person;
import com.service.IPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ramezanimatin on 8/15/2015.
*/
#Service
public class PersonService implements IPersonService {
#Autowired(required = true)
private IPersonRepository iPersonRepository;
#Override
#Transactional
public void insertPerson(Person person) {
iPersonRepository.save(person);
}
#Override
#Transactional
public void loadByEntityId(Long id) {
Person person = iPersonRepository.loadByEntityId(id);
System.out.println(person.getName());
person.setName("matin");
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>test</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.2.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.0.GA</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- jpa lib-->
</dependencies>
<build>
<finalName>test</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
My problem:
In Hibernate the Object Model has 3 states:
1- Transient
2- Persistent
3- Detached
I want to clarify the following situation:
When Object Model is fetched from the DataBase, it is Persistent. In loadByEntityId of PersonService when the Person Entity is loaded, It isn't persistent. Why?
I changed name to 'Matin' but didn't commited to DataBase.
Updated:
Thanks to M. Deinum for explain subtle differences.
Please remove this method:
private Session getSession() {
try {
return sessionFactory.getCurrentSession();
} catch (Exception e) {
return sessionFactory.openSession();
}
}
and just invoke getCurrentSession() for example:
Session session = sessionFactory.getCurrentSession();
In this method:
#Override
#Transactional
public void loadByEntityId(Long id) {
Person person = iPersonRepository.loadByEntityId(id);
System.out.println(person.getName());
person.setName("matin");
}
you have found Person entity and it's pretty much done. Under the hood you are using session in Hibernate so this particular code:
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Person e where e.id=:id");
query.setParameter("id", id);
return ((T) query.uniqueResult());
only retrieve data.
What you need to do is define update method in your repository IGenericRepository interface:
public abstract interface IGenericRepository<T, pk extends Serializable> {
public void save(T t);
public T loadByEntityId(pk id);
public void updateEntity(T t);
}
implement it in GenericRepository:
#Override
public void updateEntity(T entity) {
getSession().update(entity);
}
define in IPersonService method updatePerson and implement it in PersonService and use updateEntity from Repostitory:
#Override
#Transactional
public void updatePerson(Person person) {
iPersonRepository.updateEntity(person);
}
And now when you use loadByEntityId after you have updated Person with updatePerson you should retrieve updated entity from db.

Resources