We configured springsessions using redis as session store. With bigger load it ended in a result where users happen to get back random session data.
Unfortunately we are not able to reproduce it again and it is not reproducable in test environment.
Has anyone had similar experience and can maybe point a direction what to look at?
I have used spring session using redis session store in my project as follows ,it works normal ,i share it , hope it helps!
used spring boot starter version : 1.4.3
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>biz.paluch.redis</groupId>
<artifactId>lettuce</artifactId>
<version>3.5.0.Final</version>
</dependency>
Spring session redis configuration class :
package az.com.cybernet.aas.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.lettuce.
LettuceConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.
EnableRedisHt
tpSession;
import org.springframework.session.web.http.CookieHttpSessionStrategy;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.session.web.http.HttpSessionStrategy;
#EnableRedisHttpSession
public class RedisConfig {
#Value("${spring.redis.host}")
private String hostname;
#Value("${spring.redis.port}")
private String port;
// #Value("${spring.redis.password}")
// private String password;
#Bean
public LettuceConnectionFactory connectionFactory() {
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
connectionFactory.setHostName(hostname);
// connectionFactory.setPassword(password);
connectionFactory.setDatabase(2);
connectionFactory.setPort(Integer.parseInt(port));
return connectionFactory;
}
#Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCookieName("JSESSIONID");
serializer.setCookiePath("/");
serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
return serializer;
}
#Bean
public HttpSessionStrategy strategy() {
CookieHttpSessionStrategy cookieHttpSessionStrategy = new CookieHttpSessionStrategy();
cookieHttpSessionStrategy.setCookieSerializer(cookieSerializer());
return cookieHttpSessionStrategy;
}
}
Related
package demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Callable;
#SpringBootApplication
#Slf4j
#EnableAsync
public class DemoApplication {
#RestController
public static class MyController {
#GetMapping("/callable")
public Callable<String> callable() throws InterruptedException {
log.info("callable");
return ()-> {
log.info("async");
Thread.sleep(2000);
return "hello";
};
}
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
The code above is the spring project code.
I predicted that when http:localhost:8080/callable is called, "Hello" will be output in 2 seconds, but {} will be output.
In my console printed "Callable" but not printed "Async" Plz help me why my code not work??
i add my pom.xml file
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
WebFlux expects a Publisher(Mono/Flux) to be returned by the Controller. You can create a Mono by providing a Callable like this:
#GetMapping("/callable")
public Mono<String> callable() throws InterruptedException {
log.info("callable");
return Mono.fromCallable(() -> {
log.info("async");
Thread.sleep(2000);
return "hello";
});
}
As a side note, Thread.sleep should never be used within a reactive pipeline in actual application code.
I want to see the data in my database h2. I do not know what I'm wrong about
I have this configuration in file .properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
#spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto = update
#spring.jpa.hibernate.hbm2ddl.auto:validate
when i make a request in chrome http://localhost:8080/h2_console
i get this error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri May 10 00:37:28 BOT 2019
There was an unexpected error (type=Not Found, status=404).
No message available
this my controller:
package com.example.demo.controller;
import com.example.demo.model.Friendship;
import com.example.demo.model.User;
import com.example.demo.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.logging.Logger;
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping({"/user"})
public class UserController {
#Autowired
UserServiceImpl userServiceImpl;
static Logger log = Logger.getLogger(UserController.class.getName());
#GetMapping(path = {"/"})
public Meet getBook() {
log.info("HELLO WORDL");
return null;
}
#PostMapping("/create")
public ResponseEntity<User> createUser(#RequestBody User user) {
log.info("CREATE");
return new ResponseEntity<User>(userServiceImpl.createUser(user), HttpStatus.OK);
}
#PostMapping("/addFriend")
public ResponseEntity<User> getUser(#RequestParam("owner") Long ownerId, #RequestParam("friend") Long friendId) {
return new ResponseEntity<User>(userServiceImpl.createLinkWithFriends(ownerId, friendId), HttpStatus.OK);
}
#GetMapping("/owner/{id}/friends")
public ResponseEntity<List<User>> getFriendsOf(#PathVariable("id") Long ownerId) {
return new ResponseEntity<List<User>>(userServiceImpl.getFriendsOf(ownerId), HttpStatus.OK);
}
#GetMapping("/getUsers")
public ResponseEntity<List<User>> getUsers() {
log.info("getUser");
return new ResponseEntity<>(userServiceImpl.getUsers(), HttpStatus.OK);
}
#GetMapping("/showFriends/{id}")
public ResponseEntity<List<User>> getUsers(#PathVariable("id") int id) {
log.info("showFriends"+id);
return new ResponseEntity<>(userServiceImpl.getUsers(), HttpStatus.OK);
}
}
When I use this http://localhost:8080/user/ I get this message from the controller
Hello World!
this is my path of my project:
C:\Users\DELL\Desktop\txts\aquiesta\springTeam\traslateInClick\src\main\resources\application.properties
this is my repo https://github.com/hubmanS/traslateInClick
this is my dependency.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
According to the code below looks like your context path is also "" (blank).
#RestController
#RequestMapping({"/"})
public class MeetController{
...
}
And according to code in the controller class, the issue is with your URL mapping only. Your URL /h2_console is getting conflicted with /{id} URL of getBook method.
#GetMapping(path = {"/{id}"})
public Meet getBook(#PathVariable("id") int id) {
return null;
}
I would suggest you add the correct context path for your application so that your application URL will not get conflicted with h2-console URL. The above configurations are sometimes running and failing other times. Your console will open if h2 database context URL gets registered, if it fails to get register, you will get the error page you are getting right now.
Recommended Solution :
application.properties (Commenting other h2 attributes as they are default)
spring.h2.console.enabled=true
#spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:file:~/test
#spring.datasource.username=sa
#spring.datasource.password=
#spring.datasource.driverClassName=org.h2.Driver
spring.jpa.show-sql=true
#spring.jpa.generate-ddl=true
#spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto = update
MeetController:
package com.example.demo.controller;
import com.example.demo.model.Meet;
import com.example.demo.service.MeetServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping({"/book"})
public class MeetController {
#Autowired
MeetServiceImpl bookService;
#RequestMapping("")
public String home(){
return "Hello World!";
}
#GetMapping(path = {"/{id}"})
public Meet getBook(#PathVariable("id") int id) {
return null;
}
#PostMapping("/create/{name}/author/{id}")
public ResponseEntity<Meet> createBook() {
return null;
}
}
So your final URLs will be :
To get the book: http://localhost:8080/book/{id}/
To create a book: http://localhost:8080//create/{name}/author/{id}/
To call home: http://localhost:8080/book/
To access h2 DB Console: http://localhost:8080/h2_console/login.jsp
You have a URL mapping conflict caused by one of your GET method
#GetMapping(path = {"/{id}"})
public Meet getBook(#PathVariable("id") int id) {
return null;
}
h2_console would be mapped to getBook method as a string, and throws an exception as your method only accepts int. With RESTful naming strategy in mind, you should change your mapping to:
#GetMapping(path = {"/books/{id}"})
public Meet getBook(#PathVariable("id") int id) {
return null;
}
I have selected Jersey Test Framework to implement unit test cases for REST services.But i am getting following issue once i ran the test.
Note: I even add the resteasy-jackson-provider into pom file but couldn't help.
Here is the .pom file dependency
<!-- jersey security dependency -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- jersey test framework dependency -->
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jetty</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.3.4.Final</version>
</dependency>
<!--junit Dependency-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
MockServices.Java
#Path("/hello")
public class MockServices {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/world")
public DateVO getHello() {
DateVO j=new DateVO ();
j.setActive(true);
return j;
}
}
MockServicesTest.Java
public class MockServicesTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(MockServices.class);
}
#Test
public void test() {
Response hello = target("/hello/world").request().get();
System.out.println(hello.readEntity(String.class));//throw an above exception
}
}
Please let me know how can i overcome this problem.
Override your provider method like this
#Override
protected Application configure() {
ResourceConfig config =new ResourceConfig(MockServices.class).register(JacksonFeature.class).register("Your ContextResolver<ObjectMapper> implementation class");
return config;
}
I had to use explicitly Jersey client implementation to invoke the REST end points.
#Test
public void test() {
final Client client = new JerseyClientBuilder().build();
WebTarget target = client.target("http://localhost:9998");
final Response response =
target.path("/hello/world").request().get();
final String json = response.readEntity(String.class);
}
Reference
I am getting this error when I run my spring-mvc application :
Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
Error creating bean with name 'personDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.PersonDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
I have also checked the dependencies in my pom.xml
<!-- Spring -->
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>5.2.1.Final</hibernate.version>
Apart from this, I have specified ${spring-framework.version} and ${hibernate.version} in the version of all the dependencies
//////////////////////////////Spring Configuration//////////////
package com.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.model.Person;
import com.service.PersonService;
#Configuration
#EnableWebMvc
#ComponentScan({ "com.*" })
#EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment environment;
#Autowired
private PersonService ps;
#Bean #Autowired
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Person.class);
sessionFactory.setPackagesToScan(new String[] { "com.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean #Autowired
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("root");
dataSource.setPassword("admin123");
return dataSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/*");
}
#Bean #Autowired
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/WEB-INF/view/");
res.setSuffix(".jsp");
return res;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
return properties;
}
#Bean #Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
///////////////////////////////////POM////////////////////////////////
<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>org.springframework.samples.service.service</groupId>
<artifactId>MainAssignment3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>4.2.1.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>5.1.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
<dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId>
<version>1.1</version> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.5.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>5.5.4.Final</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
///////////////////////////////DAO File//////////////////////////////
package com.dao;
import java.util.List;
import com.model.Person;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
//////////////////////////DAO Impl///////////////////////////
package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.model.Person;
#Transactional
#Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = (Logger) LoggerFactory
.getLogger(PersonDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public void save(Person p) {
// TODO Auto-generated method stub
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(p);
tx.commit();
s.close();
System.out.println("Record successfully inserted");
}
#SuppressWarnings("deprecation")
public List<Person> list() {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
#SuppressWarnings("unchecked")
List<Person> personsList = session.createQuery("from Person").list();
for (Person p : personsList) {
logger.info("Person List::" + p);
}
return personsList;
}
public void updatePerson(Integer id) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession();
Person p = new Person();
Person person = session.get(Person.class, p.getId());
//Transaction t = session.beginTransaction();
Query query = session.createQuery("from Person");
person.setName(p.getName()); // modify the loaded object somehow
session.update(person);
//t.commit();
session.close();
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details=" + p);
return p;
}
public void removePerson(Integer id) {
Session session = sessionFactory.getCurrentSession();
// Transaction t = session.beginTransaction();
Person p = (Person) session.load(Person.class, new Integer(id));
session.delete(p);
// t.commit();
logger.info("Person deleted successfully, person details=");
}
#Transactional
public void indexPersons() throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
}
catch(Exception e)
{
throw e;
}
}
public List<Person> searchForPerson(String searchText) throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity(Person.class).get();
org.apache.lucene.search.Query query = qb
.keyword().onFields("name", "address", "salary","gender")
.matching(searchText)
.createQuery();
org.hibernate.Query hibQuery =
fullTextSession.createFullTextQuery(query, Person.class);
List<Person> results = hibQuery.list();
return results;
}
catch(Exception e)
{
throw e;
}
}
}
According to docs you should update your Spring dependency to 4.3 if you want to use Hibernate 5.2.
Also you have to correct dependencies for Hibernate search (it's releases are different then Hibernate's core).
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.5.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>5.5.4.Final</version>
</dependency>
I am trying to use arquillian-persistence-dbunit where I have to seed the database with datas but none of my solutions work. My project is based on Spring and we are using JavaConfig.
In my POM, I have the arquillian jars :
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.10.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<!-- Arquillian dependencies -->
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-persistence-dbunit</artifactId>
<version>1.0.0.Alpha7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-service-integration-spring-inject</artifactId>
<version>1.1.0.Alpha1</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-service-integration-spring-javaconfig</artifactId>
<version>1.1.0.Alpha1</version>
</dependency>
My test class :
#RunWith(Arquillian.class)
#Transactional(PersistanceTestConfig.TRANSACTION_NAME)
#SpringAnnotationConfiguration(classes = {ArquillianConfiguration.class})
#DataSource(PersistanceTestConfig.MY_DATASOURCE)
#UsingDataSet({"database/myDataset.yml"})
public class MyTestClass{
#Deployment(testable = false)
public static WebArchive createArchive(){
//returns a webArchive
}
#Test
public void myTestMethod(){
//do something
}
}
My config classes :
#Configuration
#Import({PersistanceTestConfig.class})
#ComponentScan(basePackages = {"com.myapp.dao", ""com.myapp.services"})
#EnableCaching
#EnableTransactionManagement
public class ArquillianConfiguration {}
And the PersistenceTestConfig :
public class PersistanceTestConfig {
public static final String TRANSACTION_NAME = "transaction";
public static final String MY_DATASOURCE = "datasource";
private Properties getJPAProperties() {
final Properties jpaProperties = new Properties();
jpaProperties.setProperty("hibernate.hbm2ddl.auto", "create");
jpaProperties.setProperty("hibernate.show_sql", "true");
jpaProperties.setProperty("hibernate.format_sql", "true");
jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
return jpaProperties;
}
#Bean(name = MY_DATASOURCE)
public DataSource getDataSource(){
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.continueOnError(false).ignoreFailedDrops(true).build();
}
#Bean
#Autowired
public LocalContainerEntityManagerFactoryBean getEntityManagerREFCS( DataSource dataSource) {
final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setDataSource(dataSource);
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
localContainerEntityManagerFactoryBean.setPackagesToScan("com.myapp.dao.beans");
localContainerEntityManagerFactoryBean.setPersistenceUnitName("pUnitName");
localContainerEntityManagerFactoryBean.setJpaProperties(getJPAProperties());
return localContainerEntityManagerFactoryBean;
}
}
I have tried many solutions, but I still have the same error :
org.jboss.arquillian.transaction.impl.lifecycle.TransactionProviderNotFoundException: Transaction provider for given test case has not been found.
What bothers me is there are not so many documentations on how to use arquillian-persistence-dbunit with JavaConfig. The only example that I see are badsed on xml configuration only. For instance, in this project.
Has Anyone used arquillian-persistence-dbunit with JavaConfig.