简体   繁体   中英

Spring, Hibernate, JUnit Annotated Entity

I am trying to setup a simple test environment for my JUnit , Spring, Hibernate environment. I am also trying to config the whole thing in Java and keep away from XML files for now.

So far, I was able to @Autowire @Beans , but I can't make @Entity available. I keep getting an exception saying my entity wasn't registered.

Here is a sample of what I am doing:

JpaTestConfig.java

package com.springtest.test.configuration;

import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class JpaTestConfig {


    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

      LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setDataSource(this.dataSource());
        lcemfb.setPackagesToScan(new String[] {"com.jverstry"});
    lcemfb.setPersistenceUnitName("MyTestPU");

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
    lcemfb.setJpaVendorAdapter(va);

    Properties ps = new Properties();
    ps.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    ps.put("hibernate.hbm2ddl.auto", "create");
    lcemfb.setJpaProperties(ps);

    lcemfb.afterPropertiesSet();


        return lcemfb;

    }

    @Bean
    public DataSource dataSource(){

        DriverManagerDataSource ds = new DriverManagerDataSource();

        ds.setDriverClassName("org.hsqldb.jdbcDriver");
        ds.setUrl("jdbc:hsqldb:mem:testdb");
        ds.setUsername("sa");
        ds.setPassword("");

        return ds;

    }

    @Bean
    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();
      tm.setEntityManagerFactory(this.entityManagerFactoryBean().getObject());

        return tm;

    }

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

}

ServiceConfig.java

package com.springtest.test.configuration;

import com.springtest.services.UserService;
import com.springtest.services.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {
    "com.springtest.service"
})
public class ServiceConfig {

    @Bean
    public UserService getuserService() {
        return new UserServiceImpl();
    }

}

And my test file. UserServiceTest.java

package com.springtest.test.services;

import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.springtest.pojo.User;
import com.springtest.services.UserService;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.springtest.test.configuration.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={ JpaTestConfig.class, 
                ServiceConfig.class})

public class UserServiceTest {

  @Autowired
  private UserService userService;

  @Test
  public void testCreateAndRetrieve() {
    String json = "{\"firstName\": \"John\", \"lastName\": \"Doe\"}";
    User user = userService.create(json);
    assertEquals("John", user.getFirstName());
  }
}

My Service Bean:

    package com.springtest.services;

    import java.util.List;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.PersistenceContextType;
    import javax.persistence.criteria.CriteriaQuery;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import com.google.gson.GsonBuilder;
    import com.springtest.pojo.User;

    @Service
    public class UserServiceImpl implements UserService {

        @PersistenceContext(type=PersistenceContextType.EXTENDED)
        EntityManager em;

        @Transactional
        public User create(String json) {
          User user = new GsonBuilder().create().fromJson(json, User.class);
          em.persist(user);
            return user;
        }

    }

And my Entity class:

package com.springtest.pojo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue
    private Integer id;
    private String firstName;
    private String lastName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

In a summary, how do I register the entity on my Java class @Configuration file?

Thanks,

The problem was with the package scanner on my JpaTestConfiguration file. More specifically, this line:

lcemfb.setPackagesToScan(new String[] {"com.springtest.pojo"});

is the one that will browse the packages for @Entity annotated classes. Thank you @Rembo for the tip.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM