Spring数据JPA基于Hibernate Annotation的配置

时间:2014-10-28 04:07:19

标签: spring hibernate spring-data-jpa

我正在使用spring + SpringDataJPA + Hibernate以及以下xml配置: 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 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文件.Spring Data JPA注释基础配置是这样的:

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

但是我没有用Hibernate配置它。项目代码在这里: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

但是如何整合这个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;
}

}

当我运行主课程时;碰到这个错误:

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)

1 个答案:

答案 0 :(得分:0)

<块引用>

您必须更改名称 emf => entityManagerFactory

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
  JpaTransactionManager transactionManager = new JpaTransactionManager();
  transactionManager.setEntityManagerFactory(entityManagerFactory);
  return transactionManager;
}