Unable to map List<String> by Hibernate in PostgreSql - postgresql

I would like to do easy think - map list of String in database using hibernate.
I am able to do it when my hibernate.hbm2ddl.auto is set to create or create-drop.
If i change it to update it throws me an error during building Session Factory.
I checked that columns in db exists.
During debbuging it i found that in SchemaMigratorImpl.doMigrationToTargets Hibernate method
in field namespace primaryKey for table ITEM_POSITIONS is corrupted.
Does anyone know what i am doing wrong?
Stacktrace:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: HelloWorldPU] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:877)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:805)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at util.HibernateUtil.getEntityManagerFactory(HibernateUtil.java:43)
at TestApp.main(TestApp.java:12)
Caused by: org.hibernate.exception.SQLGrammarException: Error accessing column metadata: ITEM_POSITIONS
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.convertSQLException(InformationExtractorJdbcDatabaseMetaDataImpl.java:71)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:631)
at org.hibernate.tool.schema.extract.internal.TableInformationImpl.foreignKeys(TableInformationImpl.java:88)
at org.hibernate.tool.schema.extract.internal.TableInformationImpl.getForeignKey(TableInformationImpl.java:99)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.findMatchingForeignKey(SchemaMigratorImpl.java:338)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:318)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:157)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:59)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:129)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:97)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:481)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:802)
... 5 more
Caused by: org.postgresql.util.PSQLException: ERROR: column t1.tgconstrname does not exists
Pozycja: 113
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:254)
at org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData.getImportedExportedKeys(AbstractJdbc2DatabaseMetaData.java:3373)
at org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData.getImportedKeys(AbstractJdbc2DatabaseMetaData.java:3566)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:580)
... 16 more
Configuration:
Java 8
PostgreSql: postgresql-12.1-3-windows-x64
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>hibernatemapping</groupId>
<artifactId>hibernatemapping</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.0.Final</version>
</dependency>
</dependencies>
</project>
persistence.xml:
<persistence
version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence_2_1.xsd">
<persistence-unit name="HelloWorldPU">
<class>domain.Item</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/hibernate_db?useSSL=false"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
HibernateUtil Class which is responsible for creating EntityManager:
package util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static EntityManagerFactory entityManagerFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.postgresql.Driver");
settings.put(Environment.URL, "jdbc:postgresql://localhost:5432/hibernate_db?useSSL=false");
settings.put(Environment.USER, "postgres");
settings.put(Environment.PASS, "admin");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "auto-update");
configuration.setProperties(settings);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
public static EntityManagerFactory getEntityManagerFactory(){
if (entityManagerFactory == null) {
entityManagerFactory = Persistence.createEntityManagerFactory("HelloWorldPU");
}
return entityManagerFactory;
}
}
Entity class:
package domain;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.*;
import javax.persistence.Entity;
import javax.persistence.*;
import java.util.*;
#Entity
public class Item {
#Id
#GeneratedValue(generator = "ID_GENERATOR")
#GenericGenerator(name = "ID_GENERATOR",
strategy = "enhanced-sequence",
parameters = {
#Parameter(name = "sequence_name",
value = "Item_sequence")
})
private Long id;
private String name;
#ElementCollection
#CollectionTable(name = "ITEM_POSITIONS")
#OrderColumn
#Column(name = "POSITIONS")
protected List<String> positions = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPositions() {
return positions;
}
public void setPositions(List<String> positions) {
this.positions = positions;
}
}
Test class:
import domain.Item;
import util.HibernateUtil;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import java.util.ArrayList;
import java.util.List;
public class TestApp {
public static void main(String[] args){
EntityManagerFactory emf = HibernateUtil.getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Item item = new Item();
item.setName("Item1");
List<String> positions = new ArrayList<>();
positions.add("Position1");
positions.add("Position2");
positions.add("Position3");
positions.add("Position4");
positions.add("Position5");
item.setPositions(positions);
em.persist(item);
transaction.commit();
em.close();
emf.close();
}
}
How to reproduce:
Run with property name="hibernate.hbm2ddl.auto" value="create"
Run with property name="hibernate.hbm2ddl.auto" value="update"
Set breakpoint in QueryExecutorImpl.receiveErrorResponse
Search invocation stack for SchemaMigratorImpl.doMigrationToTargets

I solved this issue.
I added this line to my pertsistence.xml
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
And i changed driver to:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>

Related

Error creating bean with name 'entityManagerFactory' defined in class path ... : Table [command_failure_notification]

When I compile my spring project, I got the following error.
Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Table [command_failure_notification] contains logical column name [user_id] referring to multiple physical column names: [user_id], ["user_id"]
I am using Eclipse and hibernate 6 and Postgres 15 Database.
I have DataBase with name "primo" and it has one table with name "test" and one column with name "id"
I wanted to connect my project to DB for fetching/save my data.
My Connection string in Application.Properties is
spring.datasource.url=jdbc:postgresql://localhost:5432/primo
spring.datasource.username=postgres
spring.datasource.password=postgres
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
My pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.</groupId>
<artifactId>DemoDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>DemoDB</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.6.Final</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
And my Java Classes:
package com.example.DemoDB;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.DemoDB.model.Test;
import jakarta.persistence.EntityManager;
#SpringBootApplication
public class DemoDbApplication {
public static void main(String[] args) {
SpringApplication.run(DemoDbApplication.class, args);
SessionFactory sf = HibernateUtil.getSessionFactory();
EntityManager entityManager = sf.createEntityManager();
entityManager.getTransaction().begin();
List<Test> result = entityManager.createQuery( "from Test", Test.class ).getResultList();
for ( Test t : result ) {
System.out.println( "Event (" + t.getId() );
}
entityManager.getTransaction().commit();
entityManager.close();
}
}
package com.example.DemoDB;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
if (sessionFactory == null)
{
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure("src/main/resources/hibernate.cfg.xml").build();
Metadata metaData = new MetadataSources(standardRegistry)
.getMetadataBuilder()
.build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
}
return sessionFactory;
}
catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
package com.example.DemoDB.model;
import java.util.Objects;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
import org.json.JSONObject;
#Entity
#NamedQuery(name = "Test.findAll", query = "SELECT u FROM Test u")
public class Test extends ADbModelEntity
{
private static final long serialVersionUID = -5165500932608878421L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
public Test() {
}
public Test(String id) {
this.id = id;
}
public String getId() {
return id;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "User [id= " + id + "]";
}
#Override
public ADbModelEntity clone() {
// TODO Auto-generated method stub
return new Test(this.id);
}
#Override
public int hashCode() {
return Objects.hash(this.id) ;
}
#Override
public boolean equals(Object other) {
if(other instanceof Test) {
return this.id.equalsIgnoreCase( ((Test)other).id );
}
return false;
}
public JSONObject toJSONObject()
{
JSONObject json = new JSONObject();
json.put("id", this.id);
return json;
}
}

Getting Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name Error using Spring Boot 2

I am using Spring Boot 2 to create web application and running the application using CommandLineRunner to connect PostgreSql database
1 . "LinkRepository" Interface:
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.entity.Link;
public interface LinkRepository extends CrudRepository<Link, Long> {
}
2. 'Link' Entity :
package com.example.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "link")
public class Link {
#Id
#GeneratedValue
#Column(name = "id")
private Long id;
#Column(name = "NAME")
private String name;
#Column(name = "url", unique = true)
private String url;
public Link(String name, String url) {
this.name = name;
this.url = url;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
3. Demo Application Config:
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.example.entity.Link;
#SpringBootApplication(scanBasePackages = { "com.example" })
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public CommandLineRunner demo(LinkRepository repository) {
// TODO Auto-generated method stub
return (args) -> {
repository.save(new Link("test", "link"));
for (Link linkrepo : repository.findAll()) {
System.out.println(linkrepo.getName());
}
};
}
}
4. Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
5. Application.properties :
spring.datasource.url=jdbc:postgresql://localhost:5432/TestDb
spring.datasource.username=postgres
spring.datasource.password=root
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto = create
spring.h2.console.enabled=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect
I am getting following error :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demo' defined in com.example.demo.DemoApplication: Unsatisfied dependency expressed through method 'demo' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'linkRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.entity.Link
If you want to use CommandLineRunner, then that should be something like this:
`#SpringBootApplication(scanBasePackages = { "com.example" })
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
return (args) -> {
repository.save(new Link("test", "link"));
for (Link linkrepo : repository.findAll()) {
System.out.println(linkrepo.getName());
}
};
}
I've just prefer doing that like this:
1) Create a new class called for example DemoBootstrap
2) And it should be soemthing like this
#Component
public class DemoBootstrap implements ApplicationListener<ContextRefreshedEvent> {
private final LinkRepository categoryRepository;
public DemoBootstrap(LinkRepository linkRepository) {
this.linkRepository = linkRepository;
}
#Override
#Transactional
public void onApplicationEvent(ContextRefreshedEvent event) {
// Here add all links that should be saved
// for example
linkRepository.save(new Link("foo", "bar"));
linkRepository.save(new Link("foo2", "bar2"));
// etc
}
Add #EntityScan("com.example.entity") on DemoApplication class or move DemoApplication to 'com.example' package and then spring will scan all sub-packages.

com.mongodb.MongoSocketReadException: Prematurely reached end of stream..............How to solve

Sorry for my long post of code.
But I am just a beginner. I want to learn Spring Framework with MongoDB.
I am getting this exception but I have read some post about this problem. However, I didn't understand and how to fix it.
I haven't created application configuration. Is this the one that causes the exception?
Can anyone help me to fix this?
I am really appreciate it. Many thanks....
package com.mywebapp.dao;
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import com.mywebapp.model.Location;
import com.mywebapp.model.User;
#Repository
public interface UserRepository extends ReactiveMongoRepository<User, String>{
List<User> findAllUsers();
User findBy_id(ObjectId id);
User findByUsername(String username);
List<User> findByFirstName(String firstName);
List<User> findByLastName(String lastName);
User findByEmail(String email);
List<User> findByDateOfBirth(Date dob);
List<User> findByLocation(Location location);
}
package com.mywebapp.controller;
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mywebapp.model.Location;
import com.mywebapp.model.User;
import com.mywebapp.service.UserService;
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value="/",method = RequestMethod.GET)
public List<User> getAllUser(){
return userService.findAllUsers();
}
#RequestMapping(value="/{username}",method = RequestMethod.GET)
public User getUserByUserName(#PathVariable("username") String userName){
return userService.findByUserName(userName);
}
#RequestMapping(value="/{firstname}",method = RequestMethod.GET)
public List<User> getUserByFirstName(#PathVariable("firstname") String firstName){
return userService.findByFirstName(firstName);
}
#RequestMapping(value="/{lastname}",method = RequestMethod.GET)
public List<User> getUserByLastName(#PathVariable("lastname") String lastName){
return userService.findByLastName(lastName);
}
#RequestMapping(value="/{email}",method = RequestMethod.GET)
public User getUserByEmail(#PathVariable("email") String email){
return userService.findByEmail(email);
}
#SuppressWarnings("deprecation")
#RequestMapping(value="/{dob}",method = RequestMethod.GET)
public List<User> getUserByDOB(#PathVariable("dob") String dob) throws Exception{
Date dateOfBirth = new Date(dob);
return userService.findByDateOfBirth(dateOfBirth);
}
#RequestMapping(value="/{location}",method = RequestMethod.GET)
public List<User> getUserByLocation(#PathVariable("location") Location location){
return userService.findByLocation(location);
}
#RequestMapping(value= "/{id}", method = RequestMethod.GET)
public User getUserById(#PathVariable("id") ObjectId id) {
return userService.findById(id);
}
}
package com.mywebapp.service;
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import com.mywebapp.dao.UserRepository;
import com.mywebapp.model.Location;
import com.mywebapp.model.User;
#Service
public class UserService {
private UserRepository userRepo;
public UserService() {
}
public List<User> findAllUsers() {
return userRepo.findAllUsers();
}
public User findById(ObjectId id) {
return userRepo.findBy_id(id);
}
public User findByUserName(String username){
return userRepo.findByUsername(username);
}
public List<User> findByFirstName(String firstName){
return userRepo.findByFirstName(firstName);
}
public List<User> findByLastName(String lastName){
return userRepo.findByLastName(lastName);
}
public User findByEmail(String email){
return userRepo.findByEmail(email);
}
public List<User> findByDateOfBirth(Date dob){
return userRepo.findByDateOfBirth(dob);
}
public List<User> findByLocation(Location location){
return userRepo.findByLocation(location);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
<artifactId>MyWebApplication</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MyWebApplication</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>
<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>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Define below properties in application.properties under resources folder, replace actual values from yours. If MongoDB is default installed and there is no user name/ password then you don't need to define username and password properties.
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.username=*********
spring.data.mongodb.password=*********
spring.data.mongodb.database=demo
Update
Update repository to extend MongoRepository
#Repository
public interface UserRepository extends MongoRepository<User, ObjectId>
{
Remove List<User> findAllUsers(); from your repository.
Change all method in your service to below
public List<User> findAllUsers() {
return userRepo.findAll();
}

Unable to build entity manager factory - Rest Tomcat Jpa

I'm making a Restful web service using netbeans, tomcat, jpa and jax-rs. I have this error since I've add the <class /> tags to my persistence.xml for all of my classes (And I need them to make a select).
The error is : https://gist.github.com/anonymous/bb37c28cdb3dbdf721c5206bfa6369c3
And my persistence.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="NataRestServicePU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>model.Media</class>
<class>model.MediaTypeDB</class>
<class>model.Message</class>
<class>model.Observation</class>
<class>model.Session</class>
<class>model.Species</class>
<class>model.User</class>
<class>model.UserType</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3307/natagora?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
</properties>
</persistence-unit>
</persistence>
And this is the main dao (that worked before, didn't change anything) but without all the CRUD methods (just the read for example)
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
public class MainDAO<T> implements IMainDAO<T> {
protected Class<T> clazz;
private final EntityManagerFactory factory;
private static final String PERSISTENCE_UNIT_NAME = "NataRestServicePU";
#PersistenceContext(unitName = "NataRestServicePU")
protected EntityManager entityManager;
public MainDAO(Class<T> type){
clazz = type;
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
public void setClazz(Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
#Override
public T read(int id){
try{
newEntityManager();
return entityManager.find(clazz,id);
}finally{
closeEntityManager();
}
}
protected void closeEntityManager(){
entityManager.close();
}
protected void newEntityManager(){
entityManager = factory.createEntityManager();
}
}

JBoss Embedded jUnit testing for EJB : NameNotFoundException

I'm newbie in EJB and jUnit, and I'm trying to do Embedded testing for the simple EJB-project that running by jBoss AS 7.1.1.Final.
I've written this test:
package com.staff.test.logic;
import java.io.File;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import javax.naming.NamingException;
import org.jboss.as.embedded.EmbeddedServerFactory;
import org.jboss.as.embedded.StandaloneServer;
import org.junit.Before;
import org.junit.Test;
import com.staff.main.logic.ProjectBean;
public class ProjectBeanTest {
private StandaloneServer server;
private static EJBContainer ec;
private static Context ctx;
#Before
public void initContainer() throws Exception {
String jbossHomeDir = System.getenv("JBOSS_HOME");
System.setProperty("jboss.home","C:/eclipse/jboss-as-7.1.1.Final");
assert jbossHomeDir != null;
server = EmbeddedServerFactory.create(new File(jbossHomeDir), System.getProperties(), System.getenv(), "org.jboss.logmanager");
server.start();
ctx=server.getContext();
}
// #After
// public static void closeContainer() throws Exception {
// if (ec != null) {
// ec.close();
// }
// }
#Test
public void test() throws NamingException {
ProjectBean bean = (ProjectBean) ctx.lookup("java:global/ProjectBean");
}
}
But string
ProjectBean bean = (ProjectBean) ctx.lookup("java:global/ProjectBean") make exception:
do this exception:
javax.naming.NameNotFoundException: ProjectBean -- service jboss.naming.context.java.global.ProjectBean
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBa sedNamingStore.java:97)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java: 178)
at org.jboss.as.naming.InitialContext.lookup(InitialContext.jav a:123)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java: 214)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.staff.test.logic.ProjectBeanTest.test(ProjectBeanTest.ja va:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall( FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(Refl ectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(Fr ameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate( InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(Ru nBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271 )
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit 4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit 4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java: 63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java :236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java: 53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java: 229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.r un(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(Test Execution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTe sts(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTe sts(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(R emoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main( RemoteTestRunner.java:197)
I dont understand why this string do exception, because I'm newbie.
My project have a bean "ProjectBean" with interface "ProjectBeanLocal" and an entity "Post". And I have a file persistence.xml to work with Oracle 10g.
ProjectBean:
package com.staff.main.logic;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import com.staff.main.domain.Post;
/**
* Session Bean implementation class ProjectBean
*/
#Stateless
#LocalBean
public class ProjectBean implements ProjectBeanLocal {
#PersistenceContext(unitName="StaffPU")
EntityManager manager;
public ProjectBean()
{
Ejb3Configuration cfg = new Ejb3Configuration();
cfg.configure("StaffPU", null);
SchemaExport schemaExport = new SchemaExport(cfg.getHibernateConfiguration());
//schemaExport.setOutputFile("schema.sql");
schemaExport.create(true, true);
}
#Override
public void savePost(Post post){
manager.persist(post);
}
#Override
public Post findPost(long id) {
Post post=manager.find(Post.class, id);
return post;
}
}
Interface ProjectBeanLocal:
package com.staff.main.logic;
import javax.ejb.Local;
import com.staff.main.domain.Post;
#Local
public interface ProjectBeanLocal {
void savePost(Post post);
Post findPost(long id);
}
Entity "Post":
package com.staff.main.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
#Entity
public class Post implements Serializable{
private static final long serialVersionUID = 6767319776206583629L;
#Id
#SequenceGenerator(name="ent2seq",sequenceName="seq_post")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="ent2seq")
private long id;
#Column(nullable=false)
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And 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="StaffPU">
<jta-data-source>java:jboss/datasources/OracleDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
<!-- <property name="javax.persistence.jdbc.show_sql" value="true" /> -->
<!-- <property name="hibernate.show_sql" value="true" /> -->
</properties>
</persistence-unit>
</persistence>
You need to expose your bean with a Remote interface.
After that, you probably will need to change the JNDI entry name used to lookup the ejb reference.
You don't provide information about how the bean is deployed which, among other things, determines the binding name, but you can search the correct lookup string in the server log.
import java.io.File;
import javax.naming.InitialContext;
import org.jboss.ejb3.embedded.EJB3StandaloneBootstrap;
import org.jboss.ejb3.embedded.EJB3StandaloneDeployer;
in your pom you have to add :
<dependency>
<groupId>org.jboss.embedded</groupId>
<artifactId>jboss-embedded-all</artifactId>
<version>beta3.SP9</version>
</dependency>
<dependency>
<groupId>org.jboss.embedded</groupId>
<artifactId>thirdparty-all</artifactId>
<version>beta3.SP9</version>
</dependency>
you have to add :
embedded-jboss-beans.xml
bean.xml,default.persistence.properties
ejb3-interceptors-aop.xml
into your resources folder and jndi.properties too whtch contains :
java.naming.factory.initial=org.jnp.interfaces.LocalOnlyContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
and you test class must contains :
EJB3StandaloneBootstrap.boot(null);
EJB3StandaloneBootstrap.scanClasspath();
EJB3StandaloneBootstrap.deployXmlResource(embeded.xml)
deployer = EJB3StandaloneBootstrap.createDeployer();
deployer.getArchives().add(new File("target/classes").toURI().toURL());
deployer.create();
deployer.start();
InitialContext context = new InitialContext();
and you look up your ejb