I am using GlassFish server in Eclipse and am trying to intergerate the hibernate-release-5.1.0.Final into the JSF project. I have tried several steps but without seccuss.
I have Placed the Hibernate Jars inside the GlassFisch directrory glassfish4\bin and restarted the server.
I placed them inside the following foloder glassfish4\glassfish\bin and restarted the GlassFisch server.
I placed the Hibernate jars inside the WEB-INF/lib
I added this part .addResource("/resources/person.hbm.xml") to the CreatePersonDemo class.
I replaced the jboss-logging.jar inside the glassfish4\glassfish\modules directory with jboss-logging-3.3.0.Final.jar
CreatePersonDemo
package com.backing;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.model.Person;
public class CreatePersonDemo {
public static void main(String[] args) {
// create session factory.
// SessionFactory factory = new Configuration()
// .configure("/resources/hibernate.cfg.xml")
// .addAnnotatedClass(Person.class)
// .buildSessionFactory();
SessionFactory factory = new Configuration().configure("/resources/hibernate.cfg.xml")
.addResource("/resources/person.hbm.xml")
.addAnnotatedClass(Person.class)
.buildSessionFactory();
// create a session.
Session session = factory.getCurrentSession();
System.out.println("CreateStudentDemo");
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/GMapsYahooMeshup</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</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="current_session_context_class">thread</property>
<mapping resource="resources/person.hbm.xml" />
<!-- <mapping class ="com.Model.Person" /> -->
</session-factory>
</hibernate-configuration>
person.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="Person" table="person">
<meta attribute="class-description">
This class contains the person detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="full_name" column="full_name" type="string" />
<property name="email " column="email " type="string" />
<property name="location" column="location" type="string" />
<property name="pwd" column="pwd" type="string" />
</class>
</hibernate-mapping>
Person.Java
package com.model;
public class Person {
private int id;
private String full_name;
private String email;
private String location;
private String pwd;
public Person(int id, String full_name, String email, String location, String pwd) {
super();
this.id = id;
this.full_name = full_name;
this.email = email;
this.location = location;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
Error
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jul 17, 2016 10:24:52 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:34)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:19)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:138)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:110)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:74)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.backing.CreatePersonDemo.main(CreatePersonDemo.java:22)
Project structure
i'm working on a spring web application using spring data jpa lately
i have problems with the persistence configuration :
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = "com.servmed")
#PropertySource({ "/resources/hibernate.properties" })
#EnableJpaRepositories(basePackages = "com.servmed.repositories")
public class PersistenceConfig {
#Autowired
private Environment env;
Properties jpaProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); //allows Hibernate to generate SQL optimized for a particular relational database.
setProperty("hibernate.show_sql",env.getProperty("hibernate.show_sql"));
}
};
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setJpaVendorAdapter(vendorAdapter);
factory.setJpaProperties(jpaProperties());
factory.setPackagesToScan("com.servmed.models");
//factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory;
}
#Bean
public PlatformTransactionManager transactionManager()
{
EntityManagerFactory factory = entityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
}
i get this error and i can't seem to find what's wrong :
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/servmed/configuration/PersistenceConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory]]
PS: i noticed that the hibernate entity manger i added to libraries is depecated , should i replace with something else ?
Not entirely sure what the problem is but I believe your entity manager definition might be busted somewhere.
I use this definition that is pretty close to your. Have a look.
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(this.dataSource());
emf.setPackagesToScan("com.servmed.models");
emf.setPersistenceUnitName("MyPU");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(va);
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
jpaProperties.put("hibernate.hbm2ddl.auto", "create");
emf.setJpaProperties(jpaProperties);
emf.afterPropertiesSet();
return emf;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:property-placeholder location="classpath:datasource.properties" />
<context:annotation-config/>
<context:component-scan base-package="com.wish.anthem.hippa" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.wish.anthem.hippa.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${jpa.showSql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> -->
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- <tx:annotation-driven /> -->
<!-- <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
</map>
</property>
</bean>
</beans>
jpa.database=MYSQL
jpa.showSql=false
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/anthem
jdbc.username=root
jdbc.password=
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>anthem</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherservlet-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>anthem</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherservlet-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
<jsp:forward page="anthemlogin.htm" />
#SuppressWarnings("unchecked")
#Repository
public class CatalogDaoImpl implements CatalogDao
{
#Autowired
private SessionFactory sessionFactory;
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
#Transactional
public List<Catalog> getAllCatalogs()
{
Session session = sessionFactory.openSession();
Query query = session.createQuery("select c from Catalog c");
List<Catalog> catalogs = query.list();
session.close();
return catalogs;
}
}
#Entity
#Table(name = "h_product")
public class Product implements Serializable
{
private static final long serialVersionUID = 353305417649482096L;
#Id
#GeneratedValue
#Column(name = "ProductID", nullable = false)
private Integer productID = 0;
#Column(name = "ProductItem", nullable = false, length = 50)
private String productItem = "";
#Column(name = "ProductName", nullable = false, length = 50)
private String productName = "";
#Column(name="Title", nullable=false, length=50)
private String title = "";
#Column(name = "CreateTime", nullable = false, length = 19)
private Date createTime = Utils.getCurrentDateTimeDate();
public Integer getProductID() {
return productID;
}
public void setProductID(Integer productID) {
this.productID = productID;
}
public String getProductItem() {
return productItem;
}
public void setProductItem(String productItem) {
this.productItem = productItem;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((productID == null) ? 0 : productID.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (productID == null)
{
if (other.productID != null)
return false;
}
else if (!productID.equals(other.productID))
return false;
return true;
}
}
#Component
public class HippaServiceImpl implements HippaService
{
#Autowired
private HippaDao catalogDao;
}
#Controller
public class HippaController
{
final static Logger logger = Logger.getLogger(HippaController.class);
#Autowired
private HippaService hippaService;
#RequestMapping(value="/anthemlogin", method = RequestMethod.GET)
public String showLoginPage(HttpServletRequest request,HttpSession session)
{
logger.info("Home Page!!!!!!!!");
return "home";
}
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:datasource.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="minPoolSize" value="${jdbc.miniPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
<property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}" />
<property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}" />
<property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}" />
<property name="preferredTestQuery" value="${jdbc.preferredTestQuery}" />
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />
</bean>
<!-- JPA EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
<prop key="hibernate.search.default.directory_provider">${hibernate.search.default.directory_provider}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:component-scan base-package="com.wish" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
jdbc.miniPoolSize=1
jdbc.maxPoolSize=10
jdbc.initialPoolSize=1
jdbc.maxIdleTime=21600
jdbc.acquireIncrement=1
jdbc.acquireRetryAttempts=30
jdbc.acquireRetryDelay=1000
jdbc.testConnectionOnCheckin=true
jdbc.preferredTestQuery=select 1
jdbc.idleConnectionTestPeriod=3600
hibernate.search.default.directory_provider=com.wish.common.resource.hibernate.search.WishFSDirectoryProvider
jpa.database=MYSQL
jpa.showSql=false
hibernate.hbm2ddl.auto=update
hibernate.jdbc.fetch_size=50
hibernate.jdbc.batch_size=30
hibernate.default_batch_fetch_size=8
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/bbcrafts?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
#Service
public class OrderDao implements IOrderDao
{
#PersistenceContext
private EntityManager em;
#SuppressWarnings("unchecked")
#Override
public List<Order> getOrdersForTracking(String orderCode, String realName) throws RuntimeException
{
StringBuffer sql = new StringBuffer("select o from Order o");
sql.append(" where (o.orderCode = ?1) and (o.billingRealName like concat('%',?2,'%')");
sql.append(" or o.shippingRealName like concat('%',?3,'%'))");
sql.append(" order by o.dateTime desc");
Query query = em.createQuery(sql.toString());
query.setParameter(1, orderCode);
query.setParameter(2, realName);
query.setParameter(3, realName);
return query.getResultList();
}
TO find: Order temp = em.find(Order.class, orderID);
return temp != null ? temp : new Order();
Libs:
activation-1.1, antlr-2.7.6, antlr-runtime-3.0, aopappliance-1.0, apache-lucene, commons-collections-3.1, commons-io-2.0.1, commons-logging-1.0.4, dom4j, ejb3-persistence-1.0.2.GA, hibernate3, hibernate-annoatation-3.4.0.GA, hibernate-commons-annoatation-3.1.0.GA, hibernate-core-3.3.2.GA, hibernate-entitymanager-3.4.0.GA, hibernate-search-3.1.1.GA, hibernate-validator-3.1.0.GA, javax.transaction, jstl-1.2, log4j, log4j-1.2.13, logback, javaassist-3.4.GA, jackson-all-1.9.0, IKanalyzer-3.1.2.GA, mysql-connector-java-5.1.18-bin, org-apache-commons-logging, pinyin4j-2.5.0, slf4j-api-1.7.9, all spring jars
I am creating a simple login functionality using Spring with MongoDB. In my spring-context.xml, i defined the configuration for mongo but when I am using it inside my controller, it is showing null pointer Exception.
Spring-context.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:c="http://www.springframework.org/schema/c" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="Controller" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="welcome"/>
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<mongo:mongo host="localhost" port="27017">
<mongo:options
connections-per-host="5"
connect-timeout="30000"
max-wait-time="10000"
write-number="1"
write-timeout="0"
write-fsync="true"/>
</mongo:mongo>
<mongo:db-factory dbname="Test"
mongo-ref="mongo"
/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Controller:
#Controller
public class LoginController {
private MongoTemplate mongoTemplate;
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
private DBCollection getCollection(String collectionName)
{
System.out.println("MongoTemplate"+mongoTemplate);
return mongoTemplate.getCollection(collectionName);
}
#RequestMapping(value="/addU", method=RequestMethod.POST)
public #ResponseBody String add(#ModelAttribute("AddUser")User user, BindingResult result, ModelMap model)
{
String returnText="";
System.out.println("Inside response");
DBCollection table=getCollection("User");
BasicDBObject document = new BasicDBObject();
document.put("name", user.getName());
document.put("password", user.getPassword());
DBCursor cur = table.find(document);
if(cur.hasNext())
{
returnText="User Found Successfully";
}
else
{
returnText="User not Found";
}
return returnText;
}
}
Can anybody let me know the root cause of this error?
It looks as though you've missed the #Autowired annotation in your controller.
Try:
#Controller
public class LoginController {
private MongoTemplate mongoTemplate;
#Autowired
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
Or autowire the field directly:
#Controller
public class LoginController {
#Autowired
private MongoTemplate mongoTemplate;
first of all, i've already read all questions related with this topic in stackoverflow, but i can't find the solution. I have been working on this for days.
I have this restFull web app built with spring mvc. When i try to retrieve a User i get this error:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.src.model.UserDTO] and content type [text/html;charset=UTF-8]
org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessag eConverterExtractor.java:84)
org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:627)
org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1)
org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:454)
org.springframework.web.client.RestTemplate.execute(RestTemplate.java:409)
org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:385)
com.src.web.controller.HomeController.getHome(HomeController.java:42)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
The request never reach the server, so the problem isn't the response content-type, because there is no response. So i am loss there. I show here my classes and configs, if some info is missed, please let me know, and i will update the question. Thanks!
Client controller:
#Controller
public class HomeController extends GenericAbstractController{
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String getHome(HttpServletRequest request, Model model) {
Principal userPrincipal = request.getUserPrincipal();
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
headers.setAccept(acceptableMediaTypes);
HttpEntity<UserDTO> entity = new HttpEntity<UserDTO>(headers);
ResponseEntity<UserDTO> result = restTemplate.exchange("http://localhost:8080/rideon/users/{id}",
HttpMethod.GET, entity, UserDTO.class, userPrincipal.getName());
model.addAttribute("user", result.getBody());
return "home";
}
Server controller:
#Controller
public class UsersController {
private static final Logger LOGGER = LoggerFactory.getLogger(UsersController.class);
#Autowired
private UserService userService;
#RequestMapping(value = "users/{id}", method = RequestMethod.GET, headers = "Accept=application/xml")
#ResponseBody
public UserDTO getUser(#PathVariable("id") String id) {
return userService.getUserById(id);
}
User:
#XmlRootElement
#Entity(name = "users")
public class UserDTO implements Serializable {
#Id
private String email;
private String password;
private String name;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Application-context:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxbMarshaller" />
<property name="unmarshaller" ref="jaxbMarshaller" />
</bean>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.src.model.UserDTO</value>
<value>com.src.model.MultimediaDTO</value>
<value>com.src.model.BicycleDTO</value>
<value>com.src.model.FriendshipRequestDTO</value>
</list>
</property>
</bean>
Dependencies:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.9</version>
<scope>runtime</scope>
</dependency>
Ok I finally found the problem. The response is actually an html error page generated by a wrong security configuration. Indeed the above code seems to be ok. Thanks!
I'm new to JPA, and i got this infamous error "no persistence provider for entitymanager named". I search far and wide on google, and tried every single solution available, to no extent i'm afraid.
Stack Trace
javax.persistence.PersistenceException: No Persistence provider for EntityManager named suplink
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at com.supinfo.suplink.util.PersistenceManager.getEntityManagerFactory(PersistenceManager.java:13)
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="suplink" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/SupLink" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
<class>com.supinfo.suplink.entity.User</class>
</persistence-unit>
PersistenceManager
public class PersistenceManager {
private static EntityManagerFactory emf;
private PersistenceManager() { }
public static EntityManagerFactory getEntityManagerFactory() {
if(emf == null) {
emf = Persistence.createEntityManagerFactory("suplink");
}
return emf;
}
public static void closeEntityManagerFactory() {
if(emf != null && emf.isOpen()) emf.close();
}
}
Thanks for your help :)
try to remove the transaction-type="RESOURCE_LOCAL"
works on my machine without this code
Good luck for your graded exercise, try code underneath ;)
public class PersistenceManager {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
private static final Logger logger;
static {
emf = Persistence.createEntityManagerFactory("SupLink");
threadLocal = new ThreadLocal<EntityManager>();
logger = Logger.getLogger("SupLink");
logger.setLevel(Level.ALL);
}
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
threadLocal.set(null);
if (em != null)
em.close();
}
public static void beginTransaction() {
getEntityManager().getTransaction().begin();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static Query createQuery(String query) {
return getEntityManager().createQuery(query);
}
public static void log(String info, Level level, Throwable ex) {
logger.log(level, info, ex);
}
}