具有基于Hibernate Annotation的配置的Spring数据JPA [英] Spring data JPA with Hibernate Annotation based configuration

查看:51
本文介绍了具有基于Hibernate Annotation的配置的Spring数据JPA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有以下xml配置的spring + SpringDataJPA + Hibernate: JpaContext.xml:

I am using spring+SpringDataJPA+ Hibernate with following xml configuration: JpaContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:annotation-config />

<context:component-scan base-package="orgProfiles"/>
<jpa:repositories base-package="orgProfiles.repository" />

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="punit"/>
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
            </bean>
        </property>

        <property name="jpaPropertyMap">
            <map>
                <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
                <entry key="hibernate.hbm2ddl.auto" value="update" />
                <entry key="hibernate.format_sql" value="true" />
            </map>
        </property>

    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/orgprofiles?autoReconnect=true" />
        <property name="username" value="root" />
        <property name="password" value="" />
        </bean>

</beans>

persistence.xml:

persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persitence"
    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_2_0.xsd"
    version="2.0">

    <persistence-unit name="punit">

    </persistence-unit>

</persistence>

我想用java注释配置替换所有这些xml文件.SpringData JPA注释基础的配置是这样的:

I would like to replace all these xml file with java annotation configuration.Spring Data JPA annotation bases configuration is something like this:

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.java-config

但是我无法使用Hibernate对其进行配置.此处的项目代码: https://github.com/sudeepcv/basics-in- java-blogspot

But I am failing to configure it with Hibernate. The project code over here: https://github.com/sudeepcv/basics-in-java-blogspot

我在这里找到了有关此的一些有用的博客:http://www.baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/#javaconfig

I have found some helpful blog over here regarding this: http:/ /w w w .baeldung.com/2011/12/13/the-persistence-layer-with-spring-3-1-and-jpa/#javaconfig

但是如何与这个spring datajpa集成?

But how can I integrate with this spring datajpa?

这是我的配置:

package com.app.config;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
@ComponentScan("com.app")
public class PersistenceJPAConfig {
     @Bean
       public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
          LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
          em.setDataSource(dataSource());
          em.setPackagesToScan(new String[] { "com.app.model" });

          JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
          em.setJpaVendorAdapter(vendorAdapter);
          em.setJpaProperties(additionalProperties());

          return em;
       }

       @Bean
       public DataSource dataSource(){
          DriverManagerDataSource dataSource = new DriverManagerDataSource();
          dataSource.setDriverClassName("com.mysql.jdbc.Driver");
//        dataSource.setUrl("jdbc:mysql://localhost:3306/spring_jpa");
          dataSource.setUrl("jdbc:mysql://localhost:3306/users?autoReconnect=true");

          dataSource.setUsername( "root" );
          dataSource.setPassword( "" );
          return dataSource;
       }

       @Bean
       public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
          JpaTransactionManager transactionManager = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(emf);

          return transactionManager;
       }

       @Bean
       public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
          return new PersistenceExceptionTranslationPostProcessor();
       }

       Properties additionalProperties() {
          Properties properties = new Properties();
//        "create-drop"
          properties.setProperty("hibernate.hbm2ddl.auto","create-drop" );
          properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
          return properties;
       }

}




package com.app;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.config.PersistenceJPAConfig;
import com.app.model.Users;
import com.app.repository.UserRepository;

@Component
@Service
@Transactional
public class SpringConsoleapp {

    @Autowired
    private static UserRepository userRepository;

    public static void main(String[] args) throws Exception{




//      ApplicationContext ctx = new ClassPathXmlApplicationContext("jpaContext.xml", "applicationContext.xml");
//       ApplicationContext ctx =  new AnnotationConfigApplicationContext(HelloWorldConfig.class);
//      ApplicationContext ctx =  new AnnotationConfigApplicationContext(ApplicationConfig.class);
        ApplicationContext ctx =  new AnnotationConfigApplicationContext(PersistenceJPAConfig.class);

//  HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
//
//                helloWorld.setMessage("Hello World!");
//                helloWorld.getMessage();

                  Users userone=new Users();
//                  userone.setId(1l);
                    userone.setUname("unameabcc");
                    userone.setPassword("password");

//                  System.out.println("id"+userone.getId());

                    System.out.println("uname:"+userone.getUname());

                    System.out.println("password:"+userone.getPassword());


                    try {
                    userRepository.save(userone);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block

                        System.out.println("something wrong:");
                        e.printStackTrace();
                    }




    }

}

用户模型:

package com.app.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="users")
public class Users {
    @Id
    @GeneratedValue
private Long id;
private String uname;
private String password;
public Long getId() {
    return id;
}
public String getPassword() {
    return password;
}
public String getUname() {
    return uname;
}
public void setId(Long id) {
    this.id = id;
}
public void setPassword(String password) {
    this.password = password;
}
public void setUname(String uname) {
    this.uname = uname;
}

}

当我上主课时;遇到此错误:

When i run the main class ; run into this error :

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Oct 28, 2014 3:01:47 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Oct 28, 2014 3:01:47 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.9.Final}
Oct 28, 2014 3:01:47 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 28, 2014 3:01:47 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 28, 2014 3:01:47 PM org.hibernate.ejb.Ejb3Configuration configure
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
Oct 28, 2014 3:01:47 PM org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator instantiateExplicitConnectionProvider
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
Oct 28, 2014 3:01:48 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Oct 28, 2014 3:01:48 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Oct 28, 2014 3:01:48 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Oct 28, 2014 3:01:48 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Oct 28, 2014 3:01:48 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
uname:unameabccjava.lang.NullPointerException
password:password
something wrong:

    at com.app.SpringConsoleapp.main(SpringConsoleapp.java:54)

推荐答案

我今天发现了这个东西.

I found this today.

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);

这篇关于具有基于Hibernate Annotation的配置的Spring数据JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆