Spring boot don't let me create a repository without database - spring

I've created a project on Spring Boot.
I've two providers extending the same Abstract provider, and i load on startup the one i'm interested in via Spring Profile.
One of the providers is based on JPA, the other have his interface implemented where i make calls to webservices.
This is the interface of the provider wich i don't want to use databases:
package net.worldline.mst.metro.ds.core.massilia.provider;
import net.worldline.mst.metro.ds.core.contract.IProductRepository;
import net.worldline.mst.metro.ds.core.massilia.model.MassiliaProduct;
import org.springframework.context.annotation.Profile;
import org.springframework.data.repository.NoRepositoryBean;
#Profile("massilia")
#NoRepositoryBean
public interface MassiliaProductRepository extends IProductRepository<MassiliaProduct,String> {
}
And this is the interface for the provider using database :
package net.worldline.mst.metro.ds.core.local.provider;
import net.worldline.mst.metro.ds.core.contract.IProductRepository;
import net.worldline.mst.metro.ds.core.local.model.Product;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
import org.springframework.stereotype.Repository;
#Profile("local")
#Repository
public interface MonBoProductRepository extends IProductRepository<Product,String> {
#Query("select p.variants from Product p where p.ean = :ean")
List<Product> findVariantByEan(#Param("ean") String ean);
#Query("select p.companions from Product p where p.ean = :ean")
List<Product> findCompanionByEan(#Param("ean") String ean);
}
They extend this interface in common :
package net.worldline.mst.metro.ds.core.contract;
import net.worldline.mst.metro.ds.core.model.AbstractProduct;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.web.bind.annotation.PathVariable;
import java.io.Serializable;
import java.util.List;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.PathVariable;
import java.io.Serializable;
import java.util.List;
#NoRepositoryBean
public interface IProductRepository<T extends AbstractProduct,ID extends Serializable> extends CrudRepository<T, ID> {
#RestResource(path = "byEAN")
T findByEan(#Param("ref") Integer ean);
T findProductByEan(#PathVariable ID ean);
List<T> findVariantByEan(#PathVariable ID ean);
List<T> findCompanionByEan(#PathVariable ID ean);
}
The provider wich isn't using database have an implementation, for job reasons, i can't show you the implementation, but it calls inside webservices
Like my providers, i've two models, extending the same abstract class.
One is annoted with #Entity,#Id and co, and i don't want to add this annotations on the other class, because for me, i've precised that i didn't want any database by asking none in the application-${profile}.properties.
This is this Model i used with the bdd :
package net.worldline.mst.metro.ds.core.local.model;
import net.worldline.mst.metro.ds.core.model.AbstractProduct;
import net.worldline.mst.metro.ds.core.model.AbstractProductCharacteristic;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "PRODUCTS")
#Profile("local")
public class Product extends AbstractProduct {
private static final Logger log = LoggerFactory.getLogger(Product.class);
#ManyToMany(
fetch = FetchType.LAZY
)
#JoinTable(
name="products_to_variants",
joinColumns = #JoinColumn(name="productEan"),
inverseJoinColumns = #JoinColumn(name="productEanVariant")
)
private List<Product> variants;
#ManyToMany(
fetch = FetchType.LAZY
)
#JoinTable(
name="products_to_companions",
joinColumns = #JoinColumn(name="productEan"),
inverseJoinColumns = #JoinColumn(name="productEanCompanion")
)
private List<Product> companions;
#Column(name = "accroche")
private String accroche;
#Id
#Column(name = "ean", unique = false)
private String ean;
#Column(name = "descriptif")
private String descriptif;
#Column(name = "libelle")
#NotEmpty
private String libelle;
#Column(name = "oldPrice")
private String oldPrice;
#Column(name = "price")
#NotEmpty
//#Digits(fraction = 0, integer = 10)
private String price;
#Column(name = "stock")
private String stock;
#OneToMany(mappedBy = "ean" )
protected List<ProductCharacteristic> characteristics;
#OneToMany(mappedBy = "product" )
#NotEmpty
protected List<ProductVisual> visuals;
public List<Product> getVariants() {
return variants;
}
public void setVariants(List<Product> variants) {
this.variants = variants;
}
public List<Product> getCompanions() {
return companions;
}
public void setCompanions(List<Product> companions) {
this.companions = companions;
}
#Override
public String getAccroche() {
return accroche;
}
#Override
public void setAccroche(String accroche) {
this.accroche = accroche;
}
#Override
public String getEan() {
return ean;
}
public void setRef(String ean) {
this.ean = ean;
}
#Override
public String getLibelle() {
return libelle;
}
#Override
public void setLibelle(String libelle) {
this.libelle = libelle;
}
#Override
public String getOldPrice() {
return oldPrice;
}
#Override
public void setOldPrice(String oldPrice) {
this.oldPrice = oldPrice;
}
#Override
public String getPrice() {
return price;
}
#Override
public void setPrice(String price) {
this.price = price;
}
#Override
public String getStock() {
return stock;
}
#Override
public void setStock(String stock) {
this.stock = stock;
}
#Override
public List<? extends AbstractProductCharacteristic> getCharacteristics() {
return characteristics;
}
#Override
public List<ProductVisual> getVisuals() {
return visuals;
}
public String getDescriptif() {
return this.descriptif;
}
public void setDescriptif(String descriptif) {
this.descriptif=descriptif;
}
}
This is the model i don't want to use with a database:
package net.worldline.mst.metro.ds.core.massilia.model;
import net.worldline.mst.metro.ds.core.model.AbstractProduct;
import org.springframework.context.annotation.Profile;
import javax.persistence.*;
import java.util.List;
#Profile("massilia")
public class MassiliaProduct extends AbstractProduct {
#Override
public String getEan() { return this.ean; }
#Override
public String getLibelle() { return this.libelle; }
#Override
public String getPrice() { return this.price; }
#Override
public String getAccroche() { return this.accroche; }
#Override
public String getOldPrice() { return oldPrice; }
#Override
public String getStock() { return stock; }
#Override
public String getDescriptif() {
return descriptif;
}
#Override
public List<MassiliaCharacteristic> getCharacteristics() {
return (List<MassiliaCharacteristic>)characteristics;
}
#Override
public List<MassiliaProductVisual> getVisuals() {
return (List<MassiliaProductVisual>)visuals;
}
}
They share this model in common :
package net.worldline.mst.metro.ds.core.model;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.hateoas.core.Relation;
import java.util.List;
#Relation(value = "product", collectionRelation = "product")
public abstract class AbstractProduct extends ResourceSupport {
protected String ean;
protected String libelle;
protected String accroche;
protected String price;
protected String oldPrice;
protected String stock;
protected String descriptif;
protected List<? extends AbstractProductCharacteristic> characteristics;
protected List<? extends AbstractProductVisual> visuals;
public abstract String getEan();
public abstract String getLibelle();
public abstract String getPrice();
public abstract String getAccroche();
public abstract String getOldPrice();
public abstract String getStock();
public abstract List<? extends AbstractProductCharacteristic> getCharacteristics();
public abstract List<? extends AbstractProductVisual> getVisuals();
public abstract String getDescriptif();
public void setEan(String ean) {
this.ean = ean;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public void setPrice(String price) {
this.price = price;
}
public void setAccroche(String accroche) {
this.accroche = accroche;
}
public void setOldPrice(String oldPrice) {
this.oldPrice = oldPrice;
}
public void setStock(String stock) {
this.stock = stock;
}
public void setCharacteristics(List<? extends AbstractProductCharacteristic> characteristics) {
this.characteristics = characteristics;
}
public void setVisuals(List<? extends AbstractProductVisual> visuals) {
this.visuals = visuals;
}
public void setDescriptif(String descriptif) {
this.descriptif = descriptif;
}
}
In the application-${profile}.properties, i precise :
spring.datasource.platform = hsqldb for the jpa instance.
spring.datasource.platform = none for the instance where i call my webservices.
My problem is simple : i was hoping spring letting me do what i want by implementing the repository, but when i launch my server, spring say that my objects are not managed, so if i don't add #Entity to my model, it doesn't want to run.
So why Spring data looks like it loads JPA repository by default ?

It was a human error in fact.
I'v forgotten a spring.datasource.platform = hsqldb in my application.properties file.
I wasn't looking at it cause i'm using spring profiles so i was looking at my application-massilia.properties wich contains spring.datasource.platform = none and is listened now cause i've deleted the duplicate in the other file.

Related

SpringBoot StackOverflow error when getting entity

I have following problem. I'm new to Spring. I have created 2 entities and now using postman I want to get all books but I keep getting StackOverflowError.
Here is book model
package com.example.demo;
import jakarta.persistence.*;
import java.util.List;
#Entity
public class BookEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
#ManyToMany
private List<Author> author;
public BookEntity() {
}
public BookEntity(String title) {
this.title = title;
}
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 List<Author> getAuthor() {
return author;
}
public void setAuthor(List<Author> author) {
this.author = author;
}
}
Author class model
package com.example.demo;
import jakarta.persistence.*;
import java.util.List;
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
#ManyToMany
private List<BookEntity> book;
public Author() {
}
public Author(String name) {
this.name = 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;
}
public List<BookEntity> getBook() {
return book;
}
public void setBook(List<BookEntity> book) {
this.book = book;
}
}
repository for books
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface BookRepository extends JpaRepository<BookEntity, Long> {
}
repository for author
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface AuthorRepository extends JpaRepository<Author, Long> {
}
controller for books
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/books")
public class BookController {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public BookController(AuthorRepository authorRepository, BookRepository bookRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
}
#GetMapping
List<BookEntity> getAllBooks() {
return bookRepository.findAll();
}
}
Can you please explain what is happening? I can't get any further. I'm stuck
Well this is a common issue. The problem is that you have Book and Author related as ManyToMany. So now whenever you reach for Books, they have an Author field, and when Jackson is trying to add Author it turns out that Author has Books which again have an Author.
Im am aware of 2 ways out of here. First one is DTO you should create a class to be displayed by you controller looking somewhat like this:
public class BookDTO {
private long bookId;
private String bookTitle;
private List<AuthorDTO> authors;
// constructors getters setters
}
situation is a bit complicated because of Many to many so yo need another DTO for authors
public class AuthorDTO {
private long authorId;
private String authorName;
//constructors getters setters
}
you could use a service layer to do all of the mapping. Then you should return BookDTO in your controller.
Another way out are annotations:
#ManyToMany
#JsonManagedReference
private List<Author> author;
and
#ManyToMany
#JsonBackReference
private List<BookEntity> book;
#JsoonManaged and back References will stop Jackson from digging into another entity.
Another thing is you should consider mappedBy in one of your Entities to prevent creating 2 tables.

Why am I getting null for the date when I create a Todo entity?

What is wrong with my to-do application? I want the user to be able to add a todo and have it be saved in my MySQL database with the time it was created, but I don't know what I'm doing wrong.
I am new to learning Springboot and would appreciate any suggestions or advice.
Todo Entity:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.util.Date;
#Entity(name = "Todo")
#NoArgsConstructor
#Table(name = "todos")
public class Todo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name="description")
private String description;
#Column(name="target_date")
#CreationTimestamp
private Date targetDate;
public Todo(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
#Override
public String toString() {
return "Todo{" +
"id=" + id +
", description='" + description + '\'' +
", targetDate=" + targetDate +
'}';
}
}
Adding a Todo with Spring Data JPA
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
#Repository
#Component
public interface TodoRepository extends JpaRepository<Todo, Integer> {
#Modifying
#Query(value = "INSERT INTO todos (description) VALUES (:description)", nativeQuery=true)
#Transactional
void addTodo(#Param("description") String description);
}
TodoController
#RestController
#RequestMapping(value = "/api/v1/todos")
#AllArgsConstructor
public class TodoController {
#Autowired
private ITodoService todoService;
#PostMapping(value = "/add-todo")
public String addTodo(#RequestParam String description) {
Todo todo = new Todo();
todo.setDescription(description);
todoService.addTodo(todo);
return todo.toString();
}
after getting a post request, the target_date is getting NULL in MySQL
I assume you can solve it by using persist():
#Autowired EntityManager entityManager;
#PostMapping(value = "/add-todo")
public String addTodo(#RequestParam String description) {
Todo todo = new Todo();
todo.setDescription(description);
entityManager.persist(todo);
return todo.toString();
}

created_by is always set to null in the database and Version does not work properly

I am trying to implement one entity to see how Auditing works in spring. I have tow issues here:
First issue is that "created_by" field is always set to null in the database, although I have created a bean of AuditAware and set it to myself.
Second issue is that whenever I want to insert something into the country table, it forces me to provide the version number. It is not the behaviour I want as I expect version gets picked up by the spring itself
I appreciate if someone could help me to tackle these two issues.
AbstractMethodEntity is as follow:
package com.xx.xxx.hotel;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDateTime;
#MappedSuperclass
#EntityListeners({ AuditingEntityListener.class })
public abstract class AbstractModelEntity<U> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "created_by")
#CreatedBy
private U CreatedBy;
#Column(name = "create_date")
#CreatedDate
private LocalDateTime createdDate;
#Version
private long version;
#Column(name = "modified_by")
#LastModifiedBy
private U lastModifiedBy;
#Column(name = "modified_date")
#LastModifiedDate
private LocalDateTime lastModifiedDate;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public U getCreatedBy() {
return CreatedBy;
}
public void setCreatedBy(U createdBy) {
CreatedBy = createdBy;
}
public LocalDateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(LocalDateTime createdDate) {
this.createdDate = createdDate;
}
public U getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(U lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public LocalDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
The Country entity:
package com.xx.xxx.hotel.service.country;
import com.miraftabi.hossein.hotel.AbstractModelEntity;
import org.hibernate.envers.AuditOverride;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Audited
#AuditOverride(forClass = AbstractModelEntity.class, isAudited = true)
#Table(name = "country")
public class CountryEntity extends AbstractModelEntity<String> {
#Column(name = "name", nullable = false)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
AuditAwareImpl file:
package com.xx.xxx.hotel.service;
import org.springframework.data.domain.AuditorAware;
import java.util.Optional;
public class AuditorAwareImpl implements AuditorAware<String> {
#Override
public Optional<String> getCurrentAuditor() {
return Optional.of("Hossein");
}
}
AuditConfiguraiton file:
package com.xx.xxx.hotel.config;
import com.xx.xxx.hotel.service.AuditorAwareImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class AuditConfiguration {
#Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
RepositoryConfiguration file:
package com.xx.xxx.hotel.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.envers.repository.support.EnversRevisionRepositoryFactoryBean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
public class RepositoryConfiguration {
}
CountryRevisionRepository file:
package com.xx.xxx.hotel.service.country;
import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CountryRevisionRepository extends RevisionRepository<CountryEntity, Long, Integer> {
}
Application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/hotel
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

hibernate & spring, invalid identifier

I have stuck on dealing with DB by using hibernate orm in spring mvc environment.
I have some tables; but I'm not gonna tell you my tables(If you want, I will edit this post)
The problem is that when hibernate runs, it generates sql - I can see the sql by configuring "hbm2_ddl auto" - but the sql has invalid identifier.
select newsreplie0_.news_article# as news6_3_4_, newsreplie0_.reply# as reply1_4_,
newsreplie0_.reply# as reply1_4_3_, newsreplie0_.account_account# as account5_4_3_,
newsreplie0_.content as content4_3_, newsreplie0_.dt as dt4_3_,
newsreplie0_.news_article# as news6_4_3_, newsreplie0_.reply_at as reply4_4_3_,
account1_.account# as account1_0_0_, account1_.email as email0_0_,
account1_.passwd as passwd0_0_, accountpro2_.account# as account1_1_1_,
accountpro2_.nickname as nickname1_1_, accountsec3_.account# as account1_2_2_,
accountsec3_.activate_key as activate2_2_2_, accountsec3_.activated as activated2_2_,
accountsec3_.enabled as enabled2_2_, accountsec3_.login_failed as login5_2_2_
from news_reply newsreplie0_
left outer join
cookingstep.account account1_ on newsreplie0_.account_account#=account1_.account#
left outer join
cookingstep.account_profile accountpro2_ on account1_.account#=accountpro2_.account#
left outer join
cookingstep.account_security accountsec3_ on account1_.account#=accountsec3_.account#
where newsreplie0_.news_article#=9
{FAILED after 4 msec}
The above statement is a sql generated by hibernate. And the error is:
java.sql.SQLSyntaxErrorException:
ORA-00904: "NEWSREPLIE0_"."ACCOUNT_ACCOUNT#": Invalid Identifier
In that exception message, there is a column called "ACCOUNT_ACCOUNT#".
It should be just "ACCOUNT#", not following "ACCOUNT_".
So, how to remove the word ?
EDIT:
Thank you all for your reply. I have asked similar question before.
And I checked out that article, it seems the problem was #JoinColumn annotation missing. Now it works out.
Here is my Entities.
Account.java for user information
package com.musicovery12.cookingstep.persistence.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="account", catalog="cookingstep", uniqueConstraints= {
#UniqueConstraint(columnNames="email")
})
public class Account implements Serializable{
private static final long serialVersionUID = 1L;
private int accountId;
private String email;
private String password;
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
private AccountProfile profile;
private AccountSecurity security;
private Set<News> newsList;
private Set<NewsReply> newsReplyList;
public Account() {}
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_account")
#SequenceGenerator(name="seq_account", sequenceName="seq_account", allocationSize=1)
#Column(name="account#", unique=true, nullable=false)
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
#Column(name="email", unique=true, nullable=false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="passwd", nullable=false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#OneToMany(mappedBy="pk.account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
#OneToOne(mappedBy="account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public AccountProfile getProfile() {
return profile;
}
public void setProfile(AccountProfile profile) {
this.profile = profile;
}
#OneToOne(mappedBy="account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public AccountSecurity getSecurity() {
return security;
}
public void setSecurity(AccountSecurity security) {
this.security = security;
}
#OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public Set<News> getNewsList() {
return newsList;
}
public void setNewsList(Set<News> newsList) {
this.newsList = newsList;
}
#OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public Set<NewsReply> getNewsReplyList() {
return newsReplyList;
}
public void setNewsReplyList(Set<NewsReply> newsReplyList) {
this.newsReplyList = newsReplyList;
}
}
and NewsReply.java for news community article's reply list.
package com.musicovery12.cookingstep.persistence.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="news_reply")
public class NewsReply {
private int replyId;
private News news;
private Date date;
private String content;
private Account account;
private int replyAt;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="gen_seq")
#SequenceGenerator(name="gen_seq", sequenceName="gen_seq", allocationSize=1)
#Column(name="reply#", unique=true, nullable=false)
public int getReplyId() {
return replyId;
}
public void setReplyId(int replyId) {
this.replyId = replyId;
}
#Temporal(TemporalType.DATE)
#Column(name="dt")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Column(name="content", nullable=false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name="reply_at")
public int getReplyAt() {
return replyAt;
}
public void setReplyAt(int replyAt) {
this.replyAt = replyAt;
}
#ManyToOne
public News getNews() {
return news;
}
public void setNews(News news) {
this.news = news;
}
#ManyToOne
#JoinColumn(name="account#", referencedColumnName="account#")
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
in NewsReply.java, there was no JoinColumn annotation to point foreing key column name.
Thank you.
#ManyToOne
#JoinColumn(name="account#", referencedColumnName="account#")
public Account getAccount() {
return account;
}
This is the problem, you tell hibernate the table has a technical name of account# what is not allowed.
What you can do is to force hibernate to use that # by defining
#ManyToOne
#JoinColumn(name="`account#`", referencedColumnName="`account#`")
public Account getAccount() {
return account;
}
But this is bad style and you have to do it on the owning-side too.
Why dont you let hibernate create the entitys for you? He is much more precisly!

Maven: getting NullPointerException when trying to insert into database

I created a server side Maven project called revison-ejb and Maven client project revison-ejb-client.
Database table is already created but I get NullPointerException when trying to insert into t_player table.
Any help would be appreciated!
revison-ejb
Player.java
package edu.foot.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Entity implementation class for Entity: Player
*
*/
#Entity
#Table(name = "t_player")
public class Player implements Serializable {
private int id;
private int age;
private String nom;
private static final long serialVersionUID = 1L;
public Player() {
super();
}
public Player(int age, String nom) {
super();
this.age = age;
this.nom = nom;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getNom() {
return this.nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Override
public String toString() {
return "Player [id=" + id + ", age=" + age + ", nom=" + nom + "]";
}
}
PlayerServiceRemote.java
package edu.foot.interfaces;
import edu.foot.entities.Player;
public interface PlayerServiceRemote {
void add(Player player);
void update(Player player);
}
PlayerService
package edu.foot.interfaces.impl;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import edu.foot.entities.Player;
import edu.foot.interfaces.PlayerServiceRemote;
#Stateless
public class PlayerService implements PlayerServiceRemote {
#PersistenceContext
EntityManager em;
public void add(Player player) {
em.persist(player);
}
public void update(Player player) {
em.merge(player);
}
}
revison-ejb-client
package edu.esprit.irt.Player;
import javax.naming.InitialContext;
import edu.foot.entities.Player;
import edu.foot.interfaces.PlayerServiceRemote;
public class AddPlayer {
public static void main(String[] args) {
InitialContext ctx = null;
PlayerServiceRemote proxy = null;
String jndi = "revison-ejb/PlayerService!edu.foot.interfaces.PlayerServiceRemote";
try {
ctx = new InitialContext();
proxy = (PlayerServiceRemote) ctx.lookup(jndi);
} catch (Exception e) {
}
Player p1 = new Player(10, "Dirar");
proxy.add(p1);
}
}
the error
Exception in thread "main" java.lang.NullPointerException
at edu.esprit.irt.Player.AddPlayer.main(AddPlayer.java:25)
As you are invoking EJBs from outside of the container, you need to annotate your interface as
#Remote
public interface PlayerServiceRemote {
You can check information on when to use #Remote

Resources