I'am new to micronaut and I try to follow this little project. However I would like it to work with postgres.
My application.yml looks like this:
micronaut:
application:
name: hello-world
datasources:
default:
url: 'jdbc:postgresql://localhost:5432/test'
username: test
password: test
driver-class-name: org.postgresql.Driver
jpa:
default:
properties:
hibernate:
hbm2ddl:
auto: update
show_sql: true
I have access to the database via intellij.
In the pom.xml I have the following dependencies:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.micronaut.configuration</groupId>
<artifactId>micronaut-jdbc-hikari</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.micronaut.configuration</groupId>
<artifactId>micronaut-hibernate-jpa</artifactId>
</dependency>
Additionally it is mentioned in the link that one needs annotionProcessor, so I added this to my build profile:
<annotationProcessorPaths>
<path>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</path>
</annotationProcessorPaths>
So now everytime I try to do the following:
#PersistenceContext
private EntityManager entityManager;
I get the following error:
Caused by: io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [javax.persistence.EntityManager] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
However I already have annotation processing enabled. And I also have a #Entity-class:
#Entity
#Table(name = "users")
public class User {
#NotBlank
#Column(name = "name")
private String userName;
public User() {
}
public User(#NotBlank final String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(final String userName) {
this.userName = userName;
}
}
What exactly am I missing in my setup?
There were multiple issues with my setup.
datasource and jpa need to be at root level
The #Entity needs a #Id
So in the end the application.yml looks like this:
micronaut:
application:
name: hello-world
datasources:
default:
url: 'jdbc:postgresql://localhost:5432/test'
username: test
password: test
driver-class-name: org.postgresql.Driver
jpa:
default:
packages-to-scan:
- 'test'
properties:
hibernate:
hbm2ddl:
auto: update
show_sql: true
And the #Entity-Class needs an #Id-Attribute:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Column(name = "user_name")
private String userName;
public User() {
}
public User(#NotBlank final String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(final String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
'}';
}
}
Related
I have a simple spring boot application with two entities, CustomUser and Role, the application connects to the PostgreSQL database without any issues but no tables are created.
application.yml:
server:
port: 8082
spring:
application:
name: user-service
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/sdm-user-db
username: root
password: password
# JPA properties
jpa:
hibernate:
ddl-auto: create
show-sql: true
database: postgresql
database-platform: org.hibernate.dialect.PostgreSQLDialect
open-in-view: false
generate-ddl: true
zipkin:
base-url: http://localhost:9411/
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
hostname: localhost
CustomUser:
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#Entity
public class CustomUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
#Column(name = "id", updatable = false, nullable = false, columnDefinition = "VARCHAR(36)")
#Type(type = "uuid-char")
private UUID id;
private String name;
#Column(unique=true)
private String email;
private String password;
private String hashKey;
#ManyToMany(fetch = FetchType.EAGER)
private Collection<Role> roles = new ArrayList<Role>();
}
Role:
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#Entity
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String name;
}
pom.xml database and jpa dependencies are included
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
The application runs without any issues so I have not much to debug with.
pg admin showing empty tables for the database
here I even try the connection with the database with the intelij plugin
successful connection test with intelij plugin
then I tried a simple commandLineRunner where I save one role into the database, it fails and here is the caused by part of the error log
Caused by: org.postgresql.util.PSQLException: ERROR: relation "role" does not exist
Position : 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2675) ~[postgresql-42.3.5.jar:42.3.5]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2365) ~[postgresql-42.3.5.jar:42.3.5]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:355) ~[postgresql-42.3.5.jar:42.3.5]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:490) ~[postgresql-42.3.5.jar:42.3.5]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:408) ~[postgresql-42.3.5.jar:42.3.5]
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:167) ~[postgresql-42.3.5.jar:42.3.5]
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:135) ~[postgresql-42.3.5.jar:42.3.5]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-4.0.3.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
... 67 common frames omitted
If you are using Hibernate, setting spring.jpa.hibernate.ddl-auto to update is likely to help.
I am learning on Spring boot to insert data into MongoDB and encountered some issues. Please give me some of your advise, thank you.
pom.xml
<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.6.2</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>com.onboard.proj</groupId>
<artifactId>onboard</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
UserController.java
#RestController
public class UserController {
#Autowired
MongoService db;
#PostMapping("/create")
public User createNew(#RequestParam("name") String name, #RequestParam("role") String role){
User obj = new User(name, role);
User newObj = db.save(obj);
return newObj;
}
}
MongoService.java
#Service
public class MongoService {
#Autowired
MongoRepository repo;
public User save(User u) {
return repo.save(u);
}
}
MongoRepository.java
public class MongoRepository {
#Autowired
private MongoTemplate template;
public User save(User e) {
if(e != null) {
template.insert(e);
}
return e;
}
}
User.java
#Document
public class User {
#Id
private String id;
//#Field("name")
private String name;
//#Field("role")
private String role;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getRole() {
return role;
}
public void setName(String name) {
this.name = name;
}
public void setRole(String role) {
this.role = role;
}
public User(String name, String role) {
super();
this.name = name;
this.role = role;
}
public User() {
super();
}
}
I tried to use PostMan and did the following setting, but couldnt reach the UserController. The result from Postman is always 404, NOT FOUND.
Add the annotation #RequestMapping("/") also on class level since Spring requires a mapping for your class also, not only the method.
#RestController
#RequestMapping("/")
public class UserController {
Also you have
#RequestParam("name") String name, #RequestParam("role") String role
but in Postman you pass name and role in JSON body. It is not coded to work like this. You should pass name and role as query parameters in Postman.
#RestController
#RequestMapping("/")
public class UserController {
#Autowired
MongoService db;
#PostMapping("/create")
public User createNew(#RequestParam("name") String name, #RequestParam("role") String role){
User obj = new User(name, role);
User newObj = db.save(obj);
return newObj;
}
}
it is better to use swagger you can get endpoints easily.
I've got some trouble attempting to rebuild connection with Postgres server using Spring Boot (in Eclipse environment). Case-relevant entities look like:
1 - Specialization - web application I'm working provides with online registration for college athlete courses, so Specialization means gymnastics or sports any student can apply for upon his/her pleasure:
#Entity
#Table(name = "Specializations")
#Getter #Setter #NoArgsConstructor
public class Specialization {
#Id
#SequenceGenerator(name = "specialization_id_sequence", sequenceName = "specialization_id_sequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "specialization_id_sequence")
#Column(name = "id")
private Short id;
#Column(name="name")
private String name;
#ManyToOne
#JoinColumn(name="health_category_id", referencedColumnName = "id")
private HealthCategory category;
#Column(name="photo_file_path")
private String photoFilePath;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "specialization", cascade = CascadeType.ALL)
List <Trainer> trainerList;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "specialization", cascade = CascadeType.ALL)
List <Group> groupList;
//some hashCode() and equals() stuff here
#Override
public String toString() {
return "Specialization [id=" + id + ", name=" + name + ", min. approvable health category=" +
category.getId() + ", path=" + photoFilePath + "]";
}
2 - HealthCategory - prerequisite health class to be confirmed formally for getting admission to specialization-related engagement (different specilializations may be featured by the same health category required)
#Entity
#Table(name = "Health_categories")
#Getter #Setter #NoArgsConstructor
public class HealthCategory {
#Id
#SequenceGenerator(name = "category_id_sequence", sequenceName = "category_id_sequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "category_id_sequence")
#Column(name = "id")
private Short id;
#Column(name="name")
private String name;
#Column(name="state")
private Short state;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL)
private List <Specialization> specialization;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
#Column(name="last_update")
private Date last_update;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL)
private List <User> userList;
#Override
public String toString() {
return "Health category [id=" + id + ", name=" + name + ", state=" + state + ", last update on=" + last_update + "]";
}
3 - Group - specialization-related group a student sign in to pass the course
#Entity
#Table(name = "Groups")
#Getter #Setter #NoArgsConstructor
public class Group {
#Id
#SequenceGenerator(name = "groupIdSequence", sequenceName = "groupIdSequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "groupIdSequence")
#Column(name = "group_id")
private Long group_id;
// eventual values: "open", "close"
#Column(name="registration_status")
private String registrationStatus;
// admission quota
#Column(name="target_size")
private Integer targetSize;
// real group size evaluation at the moment
#Column(name="actual_size")
private Integer actualSize;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "group", cascade = CascadeType.ALL)
private List <User> userList;
#ManyToOne
#JoinColumn(name="group_specialization_id", referencedColumnName = "id", nullable = false, unique = true)
private Specialization specialization;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name="schedules",
joinColumns = { #JoinColumn(name = "group_id") },
inverseJoinColumns = { #JoinColumn(name="schedule_id", nullable = false) })
private List<GroupSchedule> scheduleList;
#ManyToMany(mappedBy = "groupList")
private List<Trainer> trainerList;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name="locations",
joinColumns = { #JoinColumn(name = "group_id", nullable = false) },
inverseJoinColumns = { #JoinColumn(name="location_id", nullable = false) })
private List<Location> locationList;
#Column(name="description")
private String desciption;
4 - Trainer - an instructor concerned of holding lessons for respective groups of student who take specific course:
#Entity
#Table(name = "Trainers")
#Getter #Setter #NoArgsConstructor
public class Trainer {
#Id
#SequenceGenerator(name = "trainerIdSequence", sequenceName = "trainerIdSequence", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "trainerIdSequence")
#Column(name = "trainer_id")
private Short trainer_id;
#Column(name="first_name")
private String firstName;
#Column(name="second_name")
private String secondName;
#Column(name="last_name)")
private String lastName;
#Column(name="photo_file_path")
private String photoFilePath;
#ManyToOne
#JoinColumn(name="specialization_id", referencedColumnName = "id", nullable = false, unique = true)
private Specialization specialization;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(
name="groups",
joinColumns = { #JoinColumn(name = "trainer_id", nullable = false) },
inverseJoinColumns = { #JoinColumn(name="group_id", nullable = false) })
private List<Group> groupList;
Because of difficulties when running code with Specialization objects, SpecializationService to be posted here:
#Service
public class SpecializationService {
#Autowired
private SpecializationRepository specializationRepository;
public SpecializationService(SpecializationRepository specializationRepository) {
this.specializationRepository = specializationRepository;
}
public void createSpecialization(Specialization specialization) {
specializationRepository.save(specialization);
}
public List<Specialization> findALL() {
return (List<Specialization>) specializationRepository.findAll();
}
public List<Specialization> getSpecializations() {
List<Specialization> specializations = new ArrayList<>();
specializationRepository.findAll().forEach(specializations::add);
return specializations;
}
}
SpecializationController code:
#RestController
public class SpecializationController {
#Autowired
SpecializationService specializationService;
#RequestMapping("/specialization")
public List<Specialization> getSpecializations() {
return specializationService.getSpecializations();
}
#RequestMapping(method = RequestMethod.POST, value = "/specialization/create")
public void createSpecialization(#RequestBody Specialization spec) {
specializationService.createSpecialization(spec);
}
}
Additively, there is relevant sql create table stuff:
CREATE SEQUENCE category_id_sequence;
CREATE TABLE Health_Categories (
id SMALLINT NOT NULL DEFAULT nextval('category_id_sequence') PRIMARY KEY,
name VARCHAR(30) DEFAULT NULL,
state SMALLINT NOT NULL,
last_update TIMESTAMP
);
-- Specialization --
CREATE SEQUENCE specialization_id_sequence;
CREATE TABLE Specializations (
id SMALLINT NOT NULL DEFAULT nextval('specialization_id_sequence') PRIMARY KEY,
name VARCHAR(50) DEFAULT NULL,
health_category_id SMALLINT REFERENCES health_categories (id),
photo_file_path VARCHAR(50) DEFAULT NULL,
CONSTRAINT specialization_ibfk_1 FOREIGN KEY (id) REFERENCES health_categories (id)
);
Once executing #SpringBootApplication class as follows:
#SpringBootApplication
public class DatabaseComponentsApplication {
#Autowired
private HealthCategoryService categoryService;
#Autowired
private SpecializationService specializationService;
public static void main(String[] args) {
SpringApplication.run(DatabaseComponentsApplication.class, args);
}
#EventListener(ApplicationReadyEvent.class)
private void testJpaMethods() {
HealthCategory cat2 = new HealthCategory();
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
cat2.setLast_update(ts);
cat2.setName("Test2");
cat2.setSpecialization(null);
cat2.setState((short) 8);
categoryService.createCategory(cat2);
Specialization spec = new Specialization();
spec.setCategory(cat2);
spec.setName("Soccer");
spec.setPhotoFilePath(null);
specializationService.createSpecialization(spec);
specializationService.getSpecializations().forEach(it -> System.out.println(it));
}
}
it complains due to wrongness I still can't figure out to manage:
Caused by: org.postgresql.util.PSQLException: error: syntax error at or near: ")" Position: 209
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2505) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2241) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:158) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:108) ~[postgresql-42.2.9%20(1).jar:42.2.9]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.1.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.9.Final.jar:5.4.9.Final]
... 74 common frames omitted
Could you share your ideas what syntax issue causes that?
EDITED: pom.xml code as follows
<?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.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>databaseComponents</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>databaseComponents</name>
<description>DAO implementation draft </description>
<properties>
<java.version>1.8</java.version>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Also, application.properties stuff:
spring.datasource.driver=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/core_database
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.main.web-application-type=none
Is there any problem with calling findAll() method.
public List<Specialization> findAll() {
return (List<Specialization>) specializationRepository.findAll();
}
Can you replace getSpecializations() method
specializationService.getSpecializations().forEach(it -> System.out.println(it));
with findALL() method
specializationService.findALL().forEach(it -> System.out.println(it));
and see if it works ?
i am developing a RESTFUL API using spring-boot for a future Angular Front-End. i am having this problem with creating my entities into postgres tables.
connectivity with the database was checked and all is fine. using mvn clean install & mvn spring-boot run commands generate normal tomcat deployment without any errors. however no tables are create
here's my code:
entity:
#Entity
#Table(name = "questions")
public class Question {
#Id
#GeneratedValue(generator = "question_generator")
#SequenceGenerator(
name = "question_generator",
sequenceName = "question_sequence",
initialValue = 1000
)
private Long id;
#NotBlank
#Size(min = 3, max = 100)
private String title;
#Column(columnDefinition = "text")
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Question() {
}
}
application.propreties:
# ===============================
# DATABASE CONNECTION
# ===============================
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
# ===============================
# JPA / HIBERNATE
# ===============================
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
# Fix Postgres JPA Error:
# Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented.
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
and here's my repo:
import model.Question;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface QuestionRepository extends JpaRepository<Question, Long> {
}
i was able to resolve this issue by changing the entity package and made it visible to the app. now it works perfectly fine.
the main package name is: com.testAppBlaBla
entities's package should be com.testAppBlaBla.model
otherwise the entity won't be generated.
Try to change spring.jpa.hibernate.ddl-auto property to create value.
The below annotation works when applying it to the field:
#OneToMany(targetEntity=TestMany.class,
cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="TESTID")
private Set<TestMany> testManys = new HashSet<TestMany>();
But fails when I place it above the getter below:
public Set<TestMany> getTestManys() {
return testManys;
}
With the following error:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: TEST, for columns: [org.hibernate.mapping.Column(testManys)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:291)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:275)
at org.hibernate.mapping.Property.isValid(Property.java:217)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:464)
at org.hibernate.mapping.RootClass.validate(RootClass.java:236)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1193)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1378)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:860)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:779)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 47 more
The Many side of the relationship:
#SuppressWarnings("serial")
#Entity
#Table(name="TESTMANY")
public class TestMany extends BaseEntityImpl{
#ManyToOne
#JoinColumn(name="TESTID", insertable=false, updatable=false)
private Test test;
I don't know why it works on the property but not on the getter and it's driving me nuts. The tables are fine and the annotation seems fine to me. Am I missing something very obvious? Could it be a version problem?
There is a basic base class but i dont think this has anything to do with it:
#MappedSuperclass
public abstract class BaseEntityImpl implements BaseEntity, Serializable {
private static final long serialVersionUID = 7887314289537012320L;
#Id #GeneratedValue(strategy = AUTO)
#Column(name = "ID")
private Long id;
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
}
I am using version 3.5.3-Final and 3.2.0.Final for the hibernate-coomons-annotations.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.3-Final version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.3-Final <version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
Does anyone have any ideas or experienced something similar? I've spent 2.5 hours of my life trying to fix this one and I predict another 12.
I'm unable to test the solution right now (I'm unfortunately stuck with a computer with less than a quadrillion gigabytes of RAM, so no Hibernate launching here), but as the doc demonstrates, your set needs a type, so instead of:
#OneToMany(targetEntity=TestMany.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="TESTID")
private Set testManys = new HashSet();
you use:
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="TESTID")
private Set<TestMany> testManys = new HashSet();
and it should do the trick. In case you don't like the Hibernate documentation, you might enjoy reading this.