I am currently trying to integrate hibernate with spring.I am using the dao design patter and mysql as database.
i am trying to add the contacte entity in the db but i got this error
Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1165)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:643)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:640)
at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:359)
at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:326)
at org.springframework.orm.hibernate5.HibernateTemplate.save(HibernateTemplate.java:640)
at biz.picosoft.daoImpl.ContacteDaoImpl.inserteContacte(ContacteDaoImpl.java:20)
at biz.picosoft.mains.TestHibernate.main(TestHibernate.java:21)
this is my context file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd
">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mailmaneger" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mysessionFactory" />
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="biz.picosoft.daoImpl.ContacteDaoImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
my main file
package biz.picosoft.mains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import biz.picosoft.daoImpl.ContacteDaoImpl;
import biz.picosoft.entity.Contacte;
public class TestHibernate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Contacte contacte=new Contacte("fatma", "test", "test", "test");
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
ContacteDaoImpl contacteDaoImpl=(ContacteDaoImpl) context.getBean("d");
contacteDaoImpl.inserteContacte(contacte) ;
}
}
my dao file
package biz.picosoft.daoImpl;
import java.util.List;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import biz.picosoft.entity.Contacte;
public class ContacteDaoImpl implements ContacteDao{
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void inserteContacte(Contacte contacte) {
// TODO Auto-generated method stub
template.save(contacte);
}
public void updateContacte(Contacte contacte) {
// TODO Auto-generated method stub
template.update( contacte );
}
public void deleteContacte(Contacte contacte) {
// TODO Auto-generated method stub
template.delete(contacte);
}
public Contacte getContacteById(int id) {
// TODO Auto-generated method stub
return template.get(Contacte.class, id);
}
public List<Contacte> getAll() {
// TODO Auto-generated method stub
return template.loadAll(Contacte.class);
}
public HibernateTemplate getTemplate() {
return template;
}
}
my Entity file
package biz.picosoft.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table( name = "Contacte")
public class Contacte {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "idContact")
long idContact;
#Column(name = "nom")
String nom;
#Column(name = "mail")
String mail;
#Column(name = "téléphone")
String téléphone;
#Column(name = "adresse")
String adresse;
public Contacte( String nom, String mail, String téléphone, String adresse) {
super();
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
}
public long getIdContact() {
return idContact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTéléphone() {
return téléphone;
}
public void setTéléphone(String téléphone) {
this.téléphone = téléphone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (idContact ^ (idContact >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contacte other = (Contacte) obj;
if (idContact != other.idContact)
return false;
return true;
}
}
my 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
http://www.springframework.org/schema/context/spring-context.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.picosoft.gestionCourrier</groupId>
<artifactId>gestion-courrier</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>maven.alfresco.com</id>
<name>Alfresco Maven Repository</name>
<url>http://maven.alfresco.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring</artifactId>
<version>5.14</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-engine</artifactId>
<version>5.14</version>
</dependency>
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>0.9</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>0.2</version>
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
Most probably you missed to trigger transaction. In your context.xml add <tx:annotation-driven/> for declarative transaction support. And add #Transactional(readOnly=false) over the ContacteDaoImpl methods.
This should solve your problem. If not, there might be something else.
i fixed this problem by changing those beans,but it seems it is like creating the tables but values are not added in the table
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
<property name="checkWriteOperations" value="false"></property>
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="packagesToScan" value="biz.picosoft.entity"/>
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
Related
I'm building a system using Spring MVC, Thymeleaf, JPA (Hibernate), and Querydsl. While I was testing everything, I came across this exception:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Serviço nulo: false
[SER_USU] - Fazendo consulta...
[SER_USU] - Dao nulo: false
Exception in thread "main" java.lang.IllegalArgumentException: No sources given
at com.querydsl.jpa.JPAQueryBase.serialize(JPAQueryBase.java:56)
at com.querydsl.jpa.JPAQueryBase.serialize(JPAQueryBase.java:50)
at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:98)
at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:94)
at com.querydsl.jpa.impl.AbstractJPAQuery.fetch(AbstractJPAQuery.java:201)
at com.regra7.st.db.dao.Dao_Usuario.getPorID(Dao_Usuario.java:35)
at com.regra7.st.servico.Ser_Usuario.cadastrar(Ser_Usuario.java:46)
at com.regra7.st.testes.TesteDAO_001.<init>(TesteDAO_001.java:43)
at com.regra7.st.testes.TesteDAO_001.main(TesteDAO_001.java:19)
Unfortunately, this is not very descriptive, and so, I do not know what to do. I've tried everything, but I do not find the solution. And yes, thats all the message (the stacktrace). Here are some files I'm using...
pom.xml (I may have some dependencies wrong, I don't know exactly):
<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.regra7</groupId>
<artifactId>Sistema_Teste_001</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!-- QUERYDSL -->
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<!-- SPRING MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- SPRING CONTEXT (SPRING CORE - TRANSIENT) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!-- POSTGRESQL DRIVER JDBC -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>
<!-- API SERVLET E JSP -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- BEAN VALIDATION -->
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
<!-- IMPLEMENTAÇÃO BEAN VALIDATION (HIBERNATE) -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- THYMELEAF -->
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<!-- THYMELEAF PARA O SPRING 4 -->
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-core -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-core</artifactId>
<version>4.1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-jpa -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-apt -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<!-- C3P0 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
</project>
spring-config.xml (app-context.xml):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- ARQUIVO DE CONFIGURAÇÃO DE CONTEXTO DE APLICAÇÃO. -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<!-- Mapeamento de recursos (arquivos css, fontes, imagens, dentre outros). -->
<!-- <mvc:resources mapping="/css/**" location="/WEB-INF/recursos/css/" /> -->
<!-- <mvc:resources mapping="/imagens/**" location="/WEB-INF/recursos/imagens/" /> -->
<!-- <mvc:resources mapping="/fontes/**" location="/WEB-INF/recursos/fontes/" /> -->
<!-- <mvc:resources mapping="/fontes/**" location="/WEB-INF/recursos/javascript/" /> -->
<!-- Possibilita o uso de anotações Spring Mvc. -->
<mvc:annotation-driven />
<!-- Alternativa a declarar PersistenceAnnotationBeanPostProcessor,
um processador de anotações que lê #PersistenceContext. -->
<context:annotation-config />
<!-- Define local para procura de componentes Spring (beans configurados
por anotações em classes). -->
<context:component-scan base-package="com.regra7.st.controle" />
<context:component-scan base-package="com.regra7.st.db.dao" />
<context:component-scan base-package="com.regra7.st.servico" />
<context:component-scan base-package="com.regra7.st.testes" />
<!-- MINHA DEFINIÇÃO COM MEUS CONVERSORES CRIADOS -->
<mvc:annotation-driven conversion-service="servicoConversao"/>
<!-- PROPERTY EDITOR NÃO FUNCIONOU, MAS ISSO SIM! -->
<bean id="servicoConversao"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.regra7.st.formularios.conversores.Cov_String_LocalDate"/>
<bean class="com.regra7.st.formularios.conversores.Cov_LocalDate_String"/>
</set>
</property>
</bean>
<!-- Template Resolver para Template Engine. -->
<!-- <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" /> <property name="suffix"
value=".html" /> <property name="templateMode" value="HTML5" /> </bean> -->
<!-- SpringResourceTemplateResolver automatically integrates with Spring's
own -->
<!-- resource resolution infrastructure, which is highly recommended. -->
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<!-- HTML is the default value, added here for the sake of clarity. -->
<property name="templateMode" value="HTML" />
<!-- Template cache is true by default. Set to false if you want -->
<!-- templates to be automatically updated when modified. -->
<property name="cacheable" value="true" />
</bean>
<!-- SpringTemplateEngine automatically applies SpringStandardDialect and -->
<!-- enables Spring's own MessageSource message resolution mechanisms. -->
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<!-- Enabling the SpringEL compiler with Spring 4.2.4 or newer can speed
up -->
<!-- execution in most scenarios, but might be incompatible with specific -->
<!-- cases when expressions in one template are reused across different
data -->
<!-- ypes, so this flag is "false" by default for safer backwards -->
<!-- compatibility. -->
<property name="enableSpringELCompiler" value="true" />
</bean>
<!-- View resolver do Thymeleaf. -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
<!-- DATA SOURCE - Implementação do C3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!-- Propriedades de conexão -->
<property name = "driverClass" value="org.postgresql.Driver" />
<property name = "jdbcUrl" value="jdbc:postgresql://localhost:5432/SistemaTeste" />
<property name = "user" value="postgres" />
<property name = "password" value="admin" />
<!-- Propriedades C3p0 -->
<property name = "initialPoolSize" value="3" />
<property name = "minPoolSize" value="5" />
<property name = "maxPoolSize" value="20" />
<property name = "maxIdleTime" value="1800" /> <!-- 1800 = 30 min -->
<property name = "maxStatements" value="50" />
</bean>
<!-- Fábrica EntityManager -->
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SistemaTeste" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.default_schema">regrast</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
</props>
</property>
</bean>
<!-- Gerenciador de transações PlatformTransactionManager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<!-- INTERCEPTADORES -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/usuario/*" />
<bean class="com.regra7.st.interceptadores.Login" />
</mvc:interceptor>
</mvc:interceptors>
</beans>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="SistemaTeste" transaction-type="RESOURCE_LOCAL">
<!-- PROVEDOR JPA -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
</persistence-unit>
</persistence>
My main test class:
public class TesteDAO_001
{
public static void main(String[] args)
{
new TesteDAO_001(); // Line 19
}
public TesteDAO_001()
{
AbstractApplicationContext ac = new ClassPathXmlApplicationContext("/META-INF/spring-config.xml");
Ser_Usuario servico = ac.getBean(Ser_Usuario.class); // Service class
// For_Cadastro is an account registration form.
For_Cadastro form = new For_Cadastro();
form.setNome("Maria Pereira Maxwell"); // Name
form.setLogin("rodrigologinsoares001");
form.setSenha1("minhasenha001001"); // Password
form.setSenha2("minhasenha001001"); // Password confirmation
form.setCpf("01234567890"); // CPF = Brazil's Social ID
form.setNascimento(LocalDate.now()); // Birthday
form.setPai(0L); // Father
form.setMae(0L); // Mother
form.setGenero(0L); // Gender
System.out.printf("Serviço nulo: %s%n" , servico == null);
servico.cadastrar(form); // Line 43
ac.close();
}
}
Service method:
#Autowired
private Dao_Usuario _daoUsu;
#Transactional(rollbackFor = Exception.class)
public void cadastrar(For_Cadastro form)
{
imprimir("Fazendo consulta...");
imprimir(String.format("Dao nulo: %s%n", this._daoUsu == null));
// This may return null.
Usuario pai = this._daoUsu.getPorID(form.getPai()); // Line 46
Usuario mae = this._daoUsu.getPorID(form.getMae());
imprimir(String.format("pai nulo: %s%n", pai == null));
imprimir(String.format("mea nulo: %s%n", mae == null));
// Usuario is a Domain Model Object. A POJO representation of a table.
Usuario usu = new Usuario(form.getCpf()); // CPF = Brazil's Social ID
usu.setGenero(Genero.getGenero(form.getGenero())); // Gender
usu.setNome(form.getNome()); // Name
usu.setLogin(form.getLogin());
usu.setSenha(form.getSenha1().getBytes()); // Password
usu.setNascimento(form.getNascimento()); // Birthday
usu.setMae(mae); // Mother
usu.setPai(pai); // Father
imprimir("Modelo criado. Salvando...");
this._daoUsu.salvarAtualizar(usu); // Save/Update
imprimir("Persistência concluída.");
}
DAO method:
#PersistenceContext
protected EntityManager _em;
#Override
public Usuario getPorID(Long id)
{
if(id == null)
{
return null;
}
return new JPAQueryFactory(this._em)
.select(QUsuario.usuario)
.where(QUsuario.usuario.id.eq(id))
.fetchOne(); // Line 32
}
I'm learning how to use Querydsl. If you need me to add any more code here, please say so. I already researched google, and also here in the community. Unfortunately I did not find anything about it. Can somebody help me, please?
Thank you for your time and patience.
EDIT
Here's my Domain Model Usuario Class:
#Entity
#Table(name="tb_usuarios")
public class Usuario
{
#Id
#SequenceGenerator(
name="ger_id_usuario" ,
sequenceName="tb_usuarios_id_seq" ,
allocationSize=1 ,
initialValue = 1)
#GeneratedValue(
strategy=GenerationType.SEQUENCE ,
generator="ger_id_usuario")
#Column(
name = "usu_id" ,
unique = true)
protected Long id;
// Name
#Column(name = "usu_nome" , unique = true)
protected String nome;
// "Business Key"
#Column(name = "usu_login" , unique = true)
protected String login;
// Password
#Column(name = "usu_senha" , unique = true)
protected byte[] senha;
// Brazil's Social ID
// "Business Key"
#Column(name = "usu_cpf" , unique = true)
protected String cpf;
// Registration moment (date and time)
#Column(name = "usu_nascimento")
protected Date nascimento;
// Gender
#Column(name = "usu_genero")
protected byte genero;
// Father of this person (it may be null).
#ManyToOne(fetch = FetchType.LAZY , cascade=CascadeType.ALL)
#JoinColumn(name = "usu_pai")
protected Usuario pai;
// Mother of this person (it may be null).
#ManyToOne(fetch = FetchType.LAZY , cascade=CascadeType.ALL)
#JoinColumn(name = "usu_mae")
protected Usuario mae;
#Column(name = "usu_cadastro")
protected Timestamp cadastro;
// Children as a father.
#OneToMany(mappedBy="pai" , fetch = FetchType.LAZY , cascade = CascadeType.ALL)
protected Set<Usuario> filhosComoPai;
// Children as a mother.
#OneToMany(mappedBy="mae" , fetch = FetchType.LAZY , cascade = CascadeType.ALL)
protected Set<Usuario> filhosComoMae;
// Required by default by JPA, public or protected constructor, with no arguments.
protected Usuario()
{
this.filhosComoPai = new HashSet<>();
this.filhosComoMae = new HashSet<>();
}
/** For anyone who works with this class, it must provide a CPF, guaranteeing uniqueness, thus preventing this class from suffering problems when it is inside collections. */
public Usuario(String cpf)
{
if(Util_Validador.isCPFValido(cpf) == false)
{
throw new IllegalArgumentException("CPF não encontra-se válido.");
}
this.cpf = cpf;
this.filhosComoPai = new HashSet<>();
this.filhosComoMae = new HashSet<>();
}
// Name
public void setNome(String nome)
{
if(Util_Validador.isNomeValido(nome, 8) == false)
{
throw new IllegalArgumentException("Nome de pessoa não encontra-se válido.");
}
this.nome = nome;
}
public void setLogin(String login)
{
if(Util_Validador.isLoginValido(login, 8) == false)
{
throw new IllegalArgumentException("Login não encontra-se válido.");
}
this.login = login;
}
// Password
public void setSenha(byte[] senha)
{
this.senha = senha;
}
// Birthday
public void setNascimento(LocalDate nascimento)
{
this.nascimento = Date.valueOf(nascimento);
}
// Gender
public void setGenero(Genero genero)
{
if(genero == null)
{
throw new NullPointerException("O gênero passado como argumento encontra-se nulo.");
}
this.genero = genero.getID();
}
/** Defines a father for this person (child).*/
public void setPai(Usuario pai)
{
// It is already?
if( this.pai == null ||
this.pai.equals(pai) == false)
{
// Remove previous father from this child.
if(this.pai != null)
{
this.pai.removeFilho(this);
}
// Defines the new father for this child.
// There may be a null assignment here!
this.pai = pai;
// Add this child to a new parent.
if(pai != null)
{
if(pai.getFilhos().contains(this) == false)
{
pai.addFilho(this);
}
}
}
}
// Same logic.
public void setMae(Usuario mae)
{
if( this.mae == null ||
this.mae.equals(mae) == false)
{
if(this.mae != null)
{
this.mae.removeFilho(this);
}
this.mae = mae;
if(mae != null)
{
if(mae.getFilhos().contains(this) == false)
{
mae.addFilho(this);
}
}
}
}
public Long getID()
{
return this.id;
}
// Name
public String getNome()
{
return this.nome;
}
public String getLogin()
{
return this.login;
}
// Password
public byte[] getSenha()
{
return this.senha;
}
// CPF = Brazil's Social ID
public String getCPF()
{
return this.cpf;
}
// Birthday
public LocalDate getNascimento()
{
return this.nascimento.toLocalDate();
}
// Gender
public Genero getGenero()
{
return Genero.getGenero(
Long.getLong(
Byte.toString(this.genero)));
}
// Father
public Usuario getPai()
{
return this.pai;
}
// Mother
public Usuario getMae()
{
return this.mae;
}
// Date and time of registration (produced by database after insertion).
public LocalDateTime getCadastro()
{
return this.cadastro.toLocalDateTime();
}
// Children of this person
public Set<Usuario> getFilhos()
{
// "Genero" is a enum type (Gender), with MALE ("HOMEM") and FEMALE ("MULHER").
if(this.getGenero() == Genero.HOMEM)
{
return Collections.unmodifiableSet(this.filhosComoPai);
}
return Collections.unmodifiableSet(this.filhosComoMae);
}
// Add a child ("filho") to this person.
public boolean addFilho(Usuario filho)
{
this.isUsuarioNula(filho);
boolean add = false;
// FATHER
if(this.getGenero() == Genero.HOMEM)
{
add = this.filhosComoPai.add(filho);
if(add)
{
if( filho.getPai() == null ||
filho.getPai().equals(this) == false)
{
Usuario paiAnterior = filho.getPai();
if(paiAnterior != null)
{
paiAnterior.removeFilho(filho);
}
filho.setPai(this);
}
}
}
// MOTHER
else
{
add = this.filhosComoMae.add(filho);
if(add)
{
if( filho.getMae() == null ||
filho.getMae().equals(this) == false)
{
Usuario maeAnterior = filho.getMae();
if(maeAnterior != null)
{
maeAnterior.removeFilho(filho);
}
filho.setMae(this);
}
}
}
return add;
}
// Removes the child ("filho") from this person.
public boolean removeFilho(Usuario filho)
{
this.isUsuarioNula(filho);
boolean rem = false;
// FATHER
if(this.getGenero() == Genero.HOMEM)
{
rem = this.filhosComoPai.remove(filho);
if(rem)
{
if( filho.getPai() == null ||
filho.getPai().equals(this) == false)
{
filho.setPai(null);
}
}
}
// MOTHER
else
{
rem = this.filhosComoMae.remove(filho);
if(rem)
{
if( filho.getMae() == null ||
filho.getMae().equals(this) == false)
{
filho.setMae(null);
}
}
}
return rem;
}
// Just to print the same message.
private void isUsuarioNula(Usuario p)
{
if(p == null)
{
throw new IllegalArgumentException("Usuario passada em argumento encontra-se nula.");
}
}
#Override
public boolean equals(Object o)
{
if (o == null)
{
return false;
}
else if (o == this)
{
return true;
}
else if (o.getClass() != this.getClass())
{
return false;
}
Usuario c = (Usuario) o;
// This ensures consistent data work, and prevents something from happening silently, without us knowing why it happened.
if(c.getCPF() == null || c.getCPF().length() <= 0)
{
throw new IllegalStateException("Valor de CPF inexistente. Uma comparação não é possível.");
}
return c.getCPF().equals(this.getCPF());
}
#Override
public int hashCode()
{
// I'm using Apacho Commons Lang.
return new HashCodeBuilder()
.append(this.getCPF()).toHashCode();
}
}
The database is already created. I'm testing this on my personal pc.
EDIT 2
I would like to share my project. Unfortunately I do not know how to use Github, and my post have almost 30k characters, so I uploaded my project (made with Eclipse Mars 2) as a war file. Here are the links:
http://www.megafileupload.com/8hon/Sistema_Teste_001.war (click on free user download to download the war file)
mirror (click on download this file to download)
To help, each package contains a file named "package-info". If in case you have any questions, check out this file. Other than that, english comments have been added for clarification.
I'm so sorry. I know it's not very convenient to download my project this way, but it was the only solution I found at the time. That way you can fully see my project.
And answering your question, I'm testing this code in the normal way, as an executable Java program. The Q classes are being generated, and my IDE is not accusing any syntax errors or anything. I'm right clicking my project and choosing "Run As..." -> "3 Java Application" to run. To generate my Q classes I'm clicking on "Run As..." -> "8 Maven generate-sources".
Well I'm embarrassed to say I didn't catch this sooner. Your syntax on your query is actually wrong
return new JPAQueryFactory(this._em)
.select(QUsuario.usuario)
.where(QUsuario.usuario.id.eq(id))
.fetchOne();
should be
return new JPAQueryFactory(this._em)
.selectFrom(QUsuario.usuario)
.where(QUsuario.usuario.id.eq(id))
.fetchOne();
Its selectFrom instead of select.
My suspicion is that the generated sources are not on the build path within your Eclipse project. Therefore when you run your Java application it is not able to find the Q source files/classes. Right click on your Eclipse Mars project and select the "Properties" option. Make sure you are on the "Source" tab and click "Add Folder" and select the target/generated-sources/java folder and Click "OK". This will add the generated-sources to your Eclipse Mars project. Then try running your Java main class.
I would like to ask about where did I go wrong in this. I just started up a simple login feature using Spring and Hibernate 4, but it seems that I always seem to get NoSuchMethodException. Tried looking up everywhere about where I go wrong, but it's like I never did get it right. Any help will be most appreciated. Below are the Codes.
bean.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"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="try*">PROPAGATION_REQUIRED,ISOLATION_READ_UNCOMMITTED,-Exception</prop>
<!-- <prop key="try*">PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE,-Exception</prop> -->
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:#db01.aprdev.com:1521:aprdev" />
<property name="username" value="training" />
<property name="password" value="training" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://localhost:1433;databaseName=test" />
<property name="username" value="sa" />
<property name="password" value="pass123" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>com/model/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> -->
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
</bean>
<bean id="userDAO" class="com.dao.impl.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="serviceProxyTemplate" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="userServiceProxy" parent="serviceProxyTemplate">
<property name="target">
<bean id="userService" class="com.services.impl.UserServiceImpl">
<property name="userDAO" ref="userDAO" />
</bean>
</property>
</bean>
User.java
package com.model;
public class User {
private String id;
private String name;
private String password;
public User() {}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserServiceImpl.java
package com.services.impl;
import java.util.List;
import com.dao.UserDAO;
import com.model.User;
import com.services.UserService;
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
public List validate(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return this.userDAO.validate(user);
}
}
UserDAOImpl.java
package com.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.dao.UserDAO;
import com.model.User;
public class UserDAOImpl implements UserDAO{
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory session) {
this.sessionFactory = session;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public List validate(User user) throws HibernateException {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where name = :name and password = :pass ");
query.setParameter("name", user.getName());
query.setParameter("pass", user.getPassword());
return query.list();
}
}
Test.java
package com.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.services.UserService;
public class SpringUtil {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext(){
if(applicationContext==null){
applicationContext = new ClassPathXmlApplicationContext("com/factory/bean.xml");
}
return applicationContext;
}
public static UserService getUserService(){
return (UserService) getApplicationContext().getBean("userServiceProxy");
}
}
Help will be much appreciated. Thank you very much!
Not sure if I've answered the problem.
Here is my test
package com.services.impl;
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.model.User;
import com.model.UserDAO;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext-test.xml")
public class StudyPointRepositoryTest {
#Autowired
private UserServiceImpl userService;
#Autowired
private UserDAO dao;
#Test
#Transactional
public void test1() {
dao.save(makeUser("Fred", "pass1"));
dao.save(makeUser("Bill", "pass2"));
dao.save(makeUser("Nobby", "pass3"));
List<User> validate = userService.validate("Fred", "pass1");
assertEquals(1, validate.size());
validate = userService.validate("Fred", "wrongpass");
assertEquals(0, validate.size());
}
private User makeUser(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return user;
}
}
Here is my config for test
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com" />
<jdbc:embedded-database id="dataSource" type="H2" />
<tx:annotation-driven />
<jpa:repositories base-package="com.model" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
Here is my DAO
package com.model;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserDAO extends CrudRepository<User, Integer> {
List<User> findByNameAndPassword(String name, String password);
}
Here is my Service
package com.services.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.User;
import com.model.UserDAO;
#Service
public class UserServiceImpl {
#Autowired
private UserDAO userDAO;
public List<User> validate(String name, String password) {
return userDAO.findByNameAndPassword(name, password);
}
}
And here is my pom, probable stuff that not needed
<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.greg</groupId>
<artifactId>jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>fmis Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<spring.data.version>1.9.2.RELEASE</spring.data.version>
<hibernate.version>5.0.6.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.190</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>jpaTest</finalName>
</build>
</project>
I've a problem with connection to mysql. This is my code:
Dependencies:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Apache Database Connection Pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<!-- MySQL JDBC Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
Context:
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.packt.app" />
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/view/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="exposeSpringMacroHelpers" value="true"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://ADMIN-PC:3306/data"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="testDAO" class="com.packt.app.DAO.Impl.TestDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
Controller:
#Controller
#RequestMapping("/tests")
public class TestController {
#Autowired
TestService testService;
#RequestMapping("/testslist.json")
public #ResponseBody List<Test> getTestList() {
return testService.getTests();
}
#RequestMapping("/layout")
public String getTestPartialPage(ModelMap modelMap) {
return "tests/layout";
}
}
Model:
#Entity
#Table(name = "test")
public class Test{
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
///gettters and setters
}
Impl:
#Repository
public class TestDAOImpl implements TestDAO {
#Autowired
private SessionFactory sessionFactory;
public TestDAOImpl() {
}
public TestDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
#Transactional
public List<Test> getTests() {
#SuppressWarnings("unchecked")
List<Test> tests = (List<Test>) sessionFactory.getCurrentSession()
.createCriteria(Test.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return tests;
}
}
Angular Controller:
var TestsController = function($scope, $http) {
$scope.test = {};
$scope.editMode = false;
$scope.fetchTestList = function() {
$http.get('tests/testslist.json').success(function(testList){
$scope.tests = testList;
});
};
$scope.resetTestForm = function() {
$scope.resetError();
$scope.test = {};
$scope.editMode = false;
};
$scope.resetError = function() {
$scope.error = false;
$scope.errorMessage = '';
};
$scope.setError = function(message) {
$scope.error = true;
$scope.errorMessage = message;
};
$scope.fetchTestList()();
$scope.predicate = 'id';
};
Hibernate config:
<?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="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.packt.app.model.Test"/>
</session-factory>
</hibernate-configuration>
Application runs without error, even when MySql Server off. In html view show me that list count "getTests" is 0. It looks like application not connection with MySQL Server. Whats wrong? Please help me.
The dialect in hibernate configuratiin is missing a L
Should be mysqlDialect i reckon.
I am reading the book Pro Spring 3 and in the chapter about Global Transactions there is some example code for persisting an object into two different mysql schemas.
I am running the code but the object is not saved in any of the two schemas.
Here is the code.
tx-jta-app-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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<context:component-scan base-package="foo.bar.service.jta"/>
<bean id="dataSourceA" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName">
<value>XADBMSA</value>
</property>
<property name="xaDataSourceClassName">
<value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="databaseName">prospring3_ch13a</prop>
<prop key="user">prospring3_ch13a</prop>
<prop key="password">prospring3_ch13a</prop>
</props>
</property>
<property name="poolSize">
<value>1</value>
</property>
</bean>
<bean id="dataSourceB" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
<property name="uniqueResourceName">
<value>XADBMSB</value>
</property>
<property name="xaDataSourceClassName">
<value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
</property>
<property name="xaProperties">
<props>
<prop key="databaseName">prospring3_ch13b</prop>
<prop key="user">prospring3_ch13b</prop>
<prop key="password">prospring3_ch13b</prop>
</props>
</property>
<property name="poolSize">
<value>1</value>
</property>
</bean>
<!-- Construct Atomikos UserTransactionManager, needed to configure Spring -->
<bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
<!-- when close is called, should we force transactions to terminate or not? -->
<property name="forceShutdown">
<value>true</value>
</property>
</bean>
<!-- Also use Atomikos UserTransactionImp, needed to configure Spring -->
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<property name="transactionTimeout">
<value>300</value>
</property>
</bean>
<!-- Configure the Spring framework to use JTA transactions from Atomikos -->
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<ref bean="atomikosTransactionManager"/>
</property>
<property name="userTransaction">
<ref bean="atomikosUserTransaction"/>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="emfBase" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" abstract="true">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="foo.bar.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.factory_class">
${com.atomikos.icatch.jta.hibernate3.AtomikosJTATransactionFactory}
</prop>
<prop key="hibernate.transaction.manager_lookup_class">
${com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup}
</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="emfA" parent="emfBase">
<property name="dataSource" ref="dataSourceA"/>
</bean>
<bean id="emfB" parent="emfBase">
<property name="dataSource" ref="dataSourceB"/>
</bean>
</beans>
foo/bar/service/jta/ContactServiceImpl.java :
package foo.bar.service.jta;
import foo.bar.domain.Contact;
import foo.bar.service.ContactService;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
#Service("contactService")
#Repository
#Transactional
public class ContactServiceImpl implements ContactService{
#PersistenceContext(unitName = "emfA")
private EntityManager emA;
#PersistenceContext(unitName = "emfB")
private EntityManager emB;
#Override
#Transactional(readOnly = true)
public List<Contact> findAll() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
#Override
#Transactional(readOnly = true)
public Contact findById(Long id) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
#Override
public Contact save(Contact contact) {
Contact contactB = new Contact();
contactB.setFirstName(contact.getFirstName());
contactB.setLastName(contact.getLastName());
if (contact.getId() == null)
{
emA.persist(contact);
emB.persist(contactB);
//throw new JpaSystemException(new PersistenceException());
}
else
{
emA.merge(contact);
emB.merge(contact);
}
return contact;
}
#Override
public long countAll() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
}
foo/bar/domain/Contact.java:
package foo.bar.domain;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import static javax.persistence.GenerationType.IDENTITY;
#Entity
#Table(name = "contact")
#NamedQueries({
#NamedQuery(name = "Contact.findAll", query="select c from Contact c"),
#NamedQuery(name = "Contact.countAll", query="select count(c) from Contact c")
})
public class Contact implements Serializable{
private Long id;
private int version;
private String firstName;
private String lastName;
private Date birthDate;
public Contact()
{
}
//getters and setters
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Version
#Column(name = "VERSION")
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal(TemporalType.DATE)
#Column(name = "BIRTH_DATE")
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
//other methods
public String toString()
{
return "Contact - Id: " + id + ", First name: " + firstName + ", Last name: " + lastName + ", Birthday: " + birthDate;
}
}
foo/bar/TxJtaSample.java:
package foo.bar;
import foo.bar.domain.Contact;
import foo.bar.service.ContactService;
import org.springframework.context.support.GenericXmlApplicationContext;
public class TxJtaSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("tx-jta-app-context.xml");
ContactService contactService = ctx.getBean("contactService", ContactService.class);
Contact contact = new Contact();
contact.setFirstName("Jta");
contact.setLastName("Manager");
contactService.save(contact);
System.out.println("Contact saved successfully");
}
}
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>foo.bar</groupId>
<artifactId>SimpleProject26</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SimpleProject26</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
<aspectj.version>1.7.2</aspectj.version>
</properties>
<dependencies>
<!-- Core Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Data -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<!-- Commons Dbcp Driver -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<!-- MySql Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<!-- JUnit testing framework -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- Logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.2</version>
</dependency>
<!-- Javax validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!-- Joda time for Hibernate 4 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-hibernate</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>3.1.0.CR6</version>
</dependency>
<!-- Google Guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
<!-- AspectJ Framework -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!-- Atomikos Transaction Framework -->
<dependency>
<groupId>com.atomikos</groupId>
<artifactId>transactions-jdbc</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>com.atomikos</groupId>
<artifactId>transactions-hibernate3</artifactId>
<version>3.8.0</version>
</dependency>
</dependencies>
<build>
<finalName>SpringApp</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</project>
The output I get on my console is the following:
http://pastebin.com/VV8ukbwy
After testing your code, I made 3 modifications, all them in the tx-jta-app-context.xml configuration file, in the declaration of the emfBase bean:
I removed the key hibernate.transaction.factory_class, as explained in this page, when you work with JPA.
I removed the ${...} around the class com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup (maybe you have a variable defined in your project, but if you haven't, you should remove them).
I added a property to the jpaProperties: <prop key="javax.persistence.transactionType">jta</prop>. #Jukka told you in his comment to have a look at a document, and at the end, they say to add this property and it works for them.
After these modifications, it works for me (I can update the 2 databases and if I generate an error during the transaction, rollback is correctly executed in both databases). I give you here the resulting definition of the emfBase bean:
<bean id="emfBase" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" abstract="true">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="foo.bar.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.manager_lookup_class">
com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup
</prop>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="javax.persistence.transactionType">jta</prop>
</props>
</property>
</bean>
I hope this can solve your problem.
Message.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name="MESSAGES")
#Cache(region = "messages", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Message {
Message(){
}
Message(String message){
message_text=message;
}
#Id #GeneratedValue
#Column(name="MESSAGE_ID")
public Long id;
#Column(name="MESSAGE_TEXT")
public String message_text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage_text() {
return message_text;
}
public void setMessage_text(String message_text) {
this.message_text = message_text;
}
}
Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="messages" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
</ehcache>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="annotation">
<properties>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#ebiz-dev-db-esb:1521:esbd"/>
<property name="hibernate.connection.username" value="CUST_INFO"/>
<property name="hibernate.connection.password" value="POUND987"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9Dialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
<property name="show_sql" value="true"/>
<property name="format_sql" value="true"/>
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.EhCacheProvider" />
<property name="hibernate.cache.provider_configuration_file_resource_path" value="ehcache.xml" />
</properties>
</persistence-unit>
</persistence>
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>HibernateWithAnnotation</groupId>
<artifactId>HibernateWithAnnotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HibernateWithAnnotation</name>
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.5</version>
</dependency>
</dependencies>
</project>
TestAnnotation class
package com.annotation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class TestAnnotation {
public static void main(String args[]){
EntityManagerFactory factory=Persistence.createEntityManagerFactory("annotation");
EntityManager manager=factory.createEntityManager();
EntityTransaction transaction=manager.getTransaction();
transaction.begin();
manager.persist(new Message("My Entity Test One More Example New"));
transaction.commit();
System.out.println("First time calling Message Object");
getMessage(manager,23);
System.out.println("Second time calling Message Object");
getMessage(manager,23);
factory.close();
}
public static void getMessage(EntityManager manager,long id){
EntityTransaction transaction1=manager.getTransaction();
transaction1.begin();
Query q=manager.createQuery("from Message m where m.id="+id);
Message m=(Message)q.getSingleResult();
System.out.println(m.getMessage_text());
transaction1.commit();
}
}
My problem is: When I run this code from TestAnnotation class via main method I get the following error:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named annotation
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.annotation.TestAnnotation.main(TestAnnotation.java:10)
Your persistence-unit is incomplete. See the documentation.
Add <class>com.annotation.TestAnnotation</class> to your persistence-unit node in your persistence.xml file before the properties node.
You likely also need transaction-type="RESOURCE_LOCAL" on you persistence-unit node.
For example, my working version uses:
pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.4-Final</version>
<scope>runtime</scope>
</dependency>
persistenct.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="MyPU" transaction-type="RESOURCE_LOCAL">
<class>com.myentities.MyEntity</class>
<properties>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<!-- These lines can be used for debugging -->
<!--<property name="show_sql" value="true"/>-->
<!--<property name="format_sql" value="true"/>-->
</properties>
</persistence-unit>
</persistence>
My DAO class:
private EntityManager m_entityManagerFactory;
// initializer (this is costly, do only 1x on post construct)
m_entityManager = createEntityManagerFactory( jdbcDriverName, jdbcURL, dbUserName, dbPassword );
// when needed (less costly, can do 1x or whenever you need the entity manager)
EntityManager entityManager = m_entityManagerFactory.createEntityManager();
private EntityManagerFactory createEntityManagerFactory (
#NotNull final String jdbcDriverName,
#NotNull final String jdbcURL,
#NotNull final String dbUserName,
#NotNull final String dbPassword )
{
final Properties properties = new Properties();
properties.put( "hibernate.connection.driver_class", jdbcDriverName );
properties.put( "hibernate.connection.url", jdbcURL );
properties.put( "hibernate.connection.username", dbUserName );
properties.put( "hibernate.connection.password", dbPassword );
return Persistence.createEntityManagerFactory( "AlertProcessorPU", properties );
}