Why do some Entities Refuse Namespacing and fall in Empyt Namespace - java

I am using the GAE Datastore for the application
I am in despair ... I hit a mental block over here and I just cant think of anything to solve this anymore. I have a class Teacher.class (and all of its CASCADES) that wont store in its Namespace ... all other classes (not shown here, but very similar) work like a charm, the Teacher.class reads and writes and all perfectly ... except if WONT go to its Namespace, it always ends up in the Empty Namespace.
I am going to post the class, along with the data interface layer.
#Entity
public class Teacher implements Serializable
{
private static final long serialVersionUID = 5426530769458891752L;
#Id
private Key key;
private long KID;
private long school;
private String FName;
private String LName;
private String Email;
private String SchoolName;
#OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private Transcript Transcript; // Contains further #OneToMany Relations and Constructors
#OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private TeacherInfo teacherInf; // Contains Only Primitive Type Objects(not important)
private Boolean ActiveUser = false;
private List<Key> WorkshopsAttended;
private List<Key> WorkshopsRegistered;
public Teacher()//Constructor
{
if(this.KID == 00)
{
this.KID = TeacherUtils.genKID();//Returns a sequence and date and location based long
this.key = KeyFactory.createKey(Teacher.class.getSimpleName(), this.KID);
this.Transcript = new Transcript();
this.teacherInf = new TeacherInfo();
}
if(this.WorkshopsAttended == null)
{
this.WorkshopsAttended = new ArrayList<Key>();
}
if(this.WorkshopsRegistered == null)
{
this.WorkshopsRegistered = new ArrayList<Key>();
}
} //End of Constructor
//Getters and Setters
}
Here is the Transcript Class
#Entity
public class Transcript implements Serializable
{
private static final long serialVersionUID = -6677626465437896027L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key ID;
#OneToOne(cascade = CascadeType.ALL, mappedBy="Transcript",fetch=FetchType.LAZY)
private Teacher teacher;
public Transcript()//Constructor
{
if(this.C1== null)
{this.C1= new Course1();}
if (this.C2== null)
{this.C2= new Course2();}
if (this.C3== null)
{this.C3= new Course3();}
}//End of Constructor
#OneToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
private Course1 C1; // Contains only primitive feilds
#OneToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
private Course2 C2; // Contains only primitive feilds
#OneToOne(cascade = CascadeType.ALL,fetch=FetchType.EAGER)
private Course3 C3;
// Getters and Setters
Now Lastly the Data Interface Layer (This is a very long long file and I cant put it all in here, so I am just gonna paste the bits that have to do with persisting Teacher entities)
public class TeacherUtils
{
private static final String ActiveNamespace = SystemSettings.TeacherActive;
private static final String DeletedNamespace = SystemSettings.TeacherDeleted;
private static final boolean NSFlag = (SystemSettings.UseNameSpace & SystemSettings.TeacherNameSpace);
public synchronized static void SaveTeacher(Teacher teacher)
{
EntityManager em = getActiveEM();
em.persist(teacher);
em.flush();
closeEM(em);
}// End of SaveTeacher
public synchronized static void UpdateTeacher(Teacher teacher)
{
EntityManager em = getActiveEM();
em.merge(teacher);
em.flush();
closeEM(em);
}// End of Update Teacher
private synchronized static EntityManager getActiveEM()
{
EntityManager em;
try
{
if( (!NamespaceManager.get().equals(ActiveNamespace)) && TeacherUtils.NSFlag)
{
setNamespace();
}
}
finally
{
em = EMF.get().createEntityManager();
em.getTransaction().begin();
}
return em;
} // End of getAciveEM();
private synchronized static void closeEM(EntityManager em)
{
em.getTransaction().commit();
em.close();
NamespaceManager.set("");
while(!NamespaceManager.get().equals(""))
{}
return;
}// End of CloseEM(em)
private synchronized static void setNamespace()
{
if(TeacherUtils.NSFlag)
{
NamespaceManager.set(TeacherUtils.ActiveNamespace);
while(!NamespaceManager.get().equals(TeacherUtils.ActiveNamespace))
{}
}
}// End of setNamespace
A typical example in the Business Logic Layer would be
Teacher teacher = new Teacher();
teacher.setFName("John");
teacher.setLName("Smith");
teacher.setEmail("xyz#xyz.com");
TeacherUtils.SaveTeacher(teacher);

I would like to thank everyone who tried looking into this question ! Turns out there was something wrong with the Teacher.class constructor logic that caused a change in the Namespace, without reverting it to its previous state (the ID generator function). Now that I took care of it all works great !! I think it's just one of those days !!
Again thanks alot and I will be leaving this code as a template incase someone needs it.

Related

Need to save two tables from different jsp pages with foreign key relationship using hibernate dao implementation method

Image of table relationship reference
After submit from bank jsp page and after submit from card jsp all in one image because of limitation of newbie
I am new to stackoverflow as well SPRING. I have tried to create two tables with foreign key concept . I have followed some examples on stackoverflow as well as from other resourcefull websites and manged to create two tables with onetomany relationship. But the problem is i have to get the first row id under cart_id column when i submit from card jsp page. Instead after submit from card jsp page there is new row created under bankadmin table and it's id is being returned. I am confused and have no idea how to correct ot resolve this issue. Please be kind and guide me. And also i have been searching for a week in stackoverflow couldn't find anything that helped me. Thanks in advance.
Bankadmin Model
#Entity
#Table(name = "bankAdmin")
public class bankAdmin implements Serializable{
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name = "bcode", nullable=false)
#Id private int bcode;
#Column (name = "bname")
private String bname;
#Column (name = "address")
private String address;
#Column (name = "phno")
private int phno;
#OneToMany(mappedBy="bankAdmin",cascade = CascadeType.ALL)
private Set<Cards> cards;
Card model
#Entity
#Table(name = "cards")
public class Cards implements Serializable {
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="cname", unique=true)
#Id private int cname;
#Column (name = "ctype")
private String ctype;
#Column (name = "min_sal")
private int min_sal;
#Column (name = "year_fee")
private int year_fee;
#Column (name = "rewards")
private String rewards;
#Column (name = "jperks")
private String jperks;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="cart_id", nullable=false)
private bankAdmin bankAdmin;
public Cards(){}
public Cards(String ctype, int min_sal, int year_fee, String rewards, String jperks, bankAdmin b){//int cname,
this.ctype=ctype;
this.min_sal=min_sal;
this.year_fee=year_fee;
this.jperks=jperks;
this.rewards=rewards;
this.bankAdmin=b;
}
public bankAdmin getBankAdmin() {
return bankAdmin;
}
public void setBankAdmin(bankAdmin bankAdmin) {
this.bankAdmin = bankAdmin;
}
CardDaoImpl
public class CardsDaoImpl implements CardsDao{
#Autowired
SessionFactory sessionfactory;
public void save(Cards cards) {
Session session = null;
Transaction tx = null;
try
{
session = this.sessionfactory.openSession();
tx = session.beginTransaction();
bankAdmin bankadmin =new bankAdmin(); //=null;
String _ctype = cards.getctype();
int _min_sal = cards.getmin_sal();
int _year_fee = cards.getyear_fee();
String _rewards = cards.getrewards();
String _jperks = cards.getjperks();
Set<Cards> card = new HashSet<Cards>();
Cards config = new Cards(_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin);
card.add(config);
bankadmin.setcards(card);
// System.out.println("bankadmin: before " + bankadmin);
// bankadmin.setbname(bankadmin.getbname());// "SBI"
// bankadmin.setphno(bankadmin.getphno());//1234567890
// bankadmin.setaddress(bankadmin.getaddress());//Bengaluru
// System.out.println("bankadmin: after " + bankadmin);
// int _cname = cards.getcname();
// int bankadmin = bankadmin.getbcode();
//_cname,_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin
// card.add(config);
// config.setBankAdmin(cards.getBankAdmin(bankadmin));
// config.setcname(cards.getcname());
// config.setctype(cards.getctype());
// config.setmin_sal(cards.getmin_sal());
// config.setyear_fee(cards.getyear_fee());
// config.setrewards(cards.getrewards());
// config.setjperks(cards.getjperks());
// config.setBankAdmin(cards.getBankAdmin());
session.save(bankadmin);
session.save(config);
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
}
finally
{
session.close();
}
}
// get lms lights config from DB
public List<Cards> Ccards() {
Session session = null;
// Transaction tx = null;
List<Cards> Ccards = null;
try{
session = this.sessionfactory.openSession();
Ccards = session.createQuery("FROM Cards").list();
System.out.println("cards dao impl executed...");
System.out.println("cards config : "+ Ccards.toString());
}
catch (Exception e)
{
System.out.println("bankAdmin Dao impl Ex : " + e);
}
finally
{
session.close();
}
return Ccards;
}
}
BankDaoImpl
public class bankAdminDaoImpl implements bankAdminDao{
#Autowired
SessionFactory sessionfactory;
public void save(bankAdmin badmin) {
Session session = null;
Transaction tx = null;
try
{
session = this.sessionfactory.openSession();
tx = session.beginTransaction();
// bankAdmin bankadmin = new bankAdmin();
bankAdmin config = new bankAdmin();
config.setbcode(badmin.getbcode());
config.setbname(badmin.getbname());
config.setaddress(badmin.getaddress());
config.setphno(badmin.getphno());
session.save(config);//save//persist
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
}
finally
{
session.close();
}
}
// get lms lights config from DB
public List<bankAdmin> BbankAdmin() {
Session session = null;
// Transaction tx = null;
List<bankAdmin> BbankAdmin = null;
try{
session = this.sessionfactory.openSession();
BbankAdmin = session.createQuery("FROM bankAdmin").list();
System.out.println("bankAdmin dao impl executed...");
System.out.println("bankAdmin config : "+ BbankAdmin.toString());
}
catch (Exception e)
{
System.out.println("bankAdmin Dao impl Ex : " + e);
}
finally
{
session.close();
}
return BbankAdmin;
}
}
Okay. I have posted the solution to your problem.
First of all, Spring framework is wonderful to work with. The framework got a lot of features, that you should take advantage of. I am not sure if I will be able to cover everything in this post, so please feel free to ask me.
I have created a simple Spring Boot application. I got total of 6 files that are important which is posted below.
Notice that I renamed your classes to CamelCase with capital starting letter. such as BankAdmin. This is considered the standard way of writing java classes. Also note that i renamed Cards to Card, so remember to rename your table in the database aswell. Also remember to rename the bankadmin table to bank_admin.
There are thee annotations that you have to look into. #Transactional, #Autowired, and PersistenceContext.
So a quick and easy explanation. #Transactional manages all transactions for you, so you do not have to begin and commit transactions. #Autowired creates objects for you, so you do not have to manage your object dependencies yourself. PersistenceContext basically creates and EntityManager for you and manages it for you. You do not have to create session nor EntitManagerFactory. These three annotations are explained very brief, so you should read about them yourself.
I also removed #Table(name = "bankAdmin") and #Table(name = "cards"). JPA can lookup these tables automatically if you follow the standard way of naming classes and database tables. It is actually pretty simple, but I still encourage you to look into this by yourself. In short, capital camelcase is turned into lowercase with _ inbetween each word that start with a capital letter. I.e. If your class name is BankAdmin then JPA will automatically look for table named bank_admin in your database.
application.properties - details about your database
spring.datasource.url=jdbc:mysql://localhost:3306/stackoverflow?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
The below code is only written to test the functionality
#SpringBootApplication
public class StackoverflowApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(StackoverflowApplication.class, args);
//Calling a class that is only made with the purpose of testing
Verification ts = ctx.getBean(Verification.class);
ts.run();
}
}
#Component
class Verification{
#Autowired
private BankAdminDao bad;
#Autowired
private CardsDao cd;
void run(){
//Create a new BankAdmin
BankAdmin ba = new BankAdmin();
ba.setAddress("someStreet");
ba.setPhno(12341234);
ba.setBname("myBanker");
//Create two cards and add them to a HashSet.
Card c1 = new Card("Visa", 1000, 1999, "Alot of", "Babes", ba);
Card c2 = new Card("Master Card", 2000, 500, "someThing", "anotherThing", ba);
Set<Card> cardList = new HashSet<>();
cardList.add(c1);
cardList.add(c2);
//Create a associatio between the BankAdmin and list of Cards
ba.setCards(cardList);
//Save them to the database.
bad.save(ba);
//Here we add a Card to an existing BankAdmin with the id 6 in the database.
//Create a new Card.
//The BankAdmin is set to null, because we not have not yet loaded the BankAdmin
Card c3 = new Card("Visa", 9999, 1337, "Alot of", "Male Babes", null);
//Save Card c3 with the BankAdmin id 6
cd.save(c3, 6);
}
}
BankAdmin
#Entity
public class BankAdmin implements Serializable{
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name = "bcode", nullable=false)
#Id private int bcode;
#Column (name = "bname")
private String bname;
#Column (name = "address")
private String address;
#Column (name = "phno")
private int phno;
#OneToMany(mappedBy="bankAdmin",cascade=CascadeType.ALL)
private Set<Card> cards;
//Getters and Setters have been removed to reduce the amount of code.
}
BankAdminDao
#Repository
//Transactional makes transaction automatical, so you do not have to begin and commit transactions yourself!
#Transactional
public class BankAdminDao{
//This makes your life a lot eaier!
//It will take care of your EntitManagerFactory and Sessions
#PersistenceContext
EntityManager em;
public void save(BankAdmin bank) {
em.merge(bank);
}
//get lms lights config from DB
public List<BankAdmin> getAllBankAdmin() {
List<BankAdmin> bankList = (List<BankAdmin>)em.createQuery("SELECT b FROM BankAdmin b");
return bankList;
}
public BankAdmin getBankAdmin(int bankId) {
return em.find(BankAdmin.class, bankId);
}
}
Card
#Entity
public class Card implements Serializable {
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="cname", unique=true)
#Id private int cname;
#Column (name = "ctype")
private String ctype;
#Column (name = "min_sal")
private int min_sal;
#Column (name = "year_fee")
private int year_fee;
#Column (name = "rewards")
private String rewards;
#Column (name = "jperks")
private String jperks;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="cart_id", nullable=false)
private BankAdmin bankAdmin;
public Card(){}
public Card(String ctype, int min_sal, int year_fee, String rewards, String jperks, BankAdmin b){
this.ctype=ctype;
this.min_sal=min_sal;
this.year_fee=year_fee;
this.jperks=jperks;
this.rewards=rewards;
this.bankAdmin=b;
}
public BankAdmin getBankAdmin() {
return bankAdmin;
}
public void setBankAdmin(BankAdmin bankAdmin) {
this.bankAdmin = bankAdmin;
}
}
CardDao
#Repository
#Transactional
public class CardsDao{
#PersistenceContext
EntityManager em;
#Autowired
BankAdminDao bad;
public void save(Card cards, int bankId) {
BankAdmin bank = bad.getBankAdmin(bankId);
cards.setBankAdmin(bank);
bank.getCards().add(cards);
em.merge(bank);
}
public List<Card> getAllCards() {
List<Card> cardList = (List<Card>)em.createQuery("SELECT c FROM Cards c");
return cardList;
}
public Card getCard(int cardId){
return em.find(Card.class, cardId);
}
}

Persisting this object doesn't persist its parameters

Here are my entities ForfaitGenerique and Offre . Those two entities are in persistence.xml (didn't put all the methods here, if needed I will add more information):
#Entity
public class ForfaitGenerique implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int idForfait;
#NotNull
private String description = "description";
#NotNull
#OneToMany(cascade = {CascadeType.ALL},fetch = FetchType.LAZY,mappedBy = "forfaitGenerique")
private List<Offre> listeOffre;
#NotNull
#ElementCollection
List<Integer> listeRemontees;
//erreur sur mon intellij mais pas d'erreur en faisant mvn clean install.On verra au test
public ForfaitGenerique() {
}
public void addOffre(Offre o) {
this.listeOffre.add(o);
}
[...]
#Entity
public class Offre implements Serializable {
#NotNull
private AgeEnum age;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#NotNull
private double nbJour;
#Enumerated(EnumType.STRING)
#NotNull
private SaisonEnum saison;
#Enumerated(EnumType.STRING)
#NotNull
private ReductionEnum reduction;
boolean consecutif;
#NotNull
private double prix;
#ManyToOne
private ForfaitGenerique forfaitGenerique;
public Offre() {
}
Here is what I am trying to persist a ForfaitGenerique ; when I persist it and then try to retrieve it through its id (which isn't null and seems to have a good value), I get a ForfaitGenerique, which is not null, but ALL stuff it should contain is null (not the id though) :
#EJB(name="databaseAccess") protected ForfaitsInterface databaseAccess;
private ForfaitGenerique f;
private Offre offre_f;
[...]
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(2);
l.add(3);
ForfaitGenerique forf = new ForfaitGenerique();
List<Offre> l_o = new ArrayList<Offre>();
forf.setListeOffre(l_o);
forf.setListeRemontees(l);
Offre o = new Offre(forf,AgeEnum.ADULTE,0.5,SaisonEnum.HAUTE,ReductionEnum.FIDELICIME,true,12.0);
forf.addOffre(o);
databaseAccess.addForfaitGenerique(forf);
int id_f = forf.getIdForfait();
assertNotNull(id_f);
System.out.println("bloublou"+id_f);
f = databaseAccess.getForfaitGenerique(id_f);
assertNotNull(f);
assertNotNull(f.getListeRemontees());//null !!
assertNotNull(f.getListeOffre());//null !!
assertEquals(f,forf);
offre_f = f.getListeOffre().get(0);
The databaseAccess object contains an entitymanager and two methods (among other), which are :
#Stateless(name="databaseAccess")
public class Forfaits implements ForfaitsInterface {
#PersistenceContext private EntityManager entityManager;
public void addForfaitGenerique(ForfaitGenerique forfaitGenerique) {
entityManager.persist(forfaitGenerique);
System.out.println("contains = "+entityManager.contains(forfaitGenerique));
}
#Override
public void addOffre(Offre o) {
entityManager.persist(o);
}
public ForfaitGenerique getForfaitGenerique(int id_forfait) {
ForfaitGenerique f = entityManager.find(ForfaitGenerique.class,id_forfait);//database.getForfaitFromId(id_forfait);
return f;
}
I think that my problem is when I am trying to persist my object, but not sure . Any help is appreciated .
In fact I just forgot to add the #Transactional(TransactionMode.COMMIT) before my test . That was the dumb solution.

Hibernate merge with flush not updating data

I've finding a solution but nothing works for me, here's the code:
Update function:
#Autowired
private SessionFactory sessionFactory;
...
public void updatePositionProfile(PositionProfile positionProfile) {
Session session = sessionFactory.getCurrentSession();
session.merge(positionProfile);
session.flush();
}
Entity (getters and setter ommited):
#Entity
#Table(name = "position_profile")
public class PositionProfile implements Serializable {
#Embeddable
public static class PositionProfile_PK implements Serializable {
private static final long serialVersionUID = 1L;
#NotNull
#Column(name="id_position")
Integer id_position;
#NotNull
#Column(name="profile")
String profile;
#NotNull
#Column(name="line")
String line;
PositionProfile_PK(){
this.id_position = 0;
this.profile = new String();
this.line = "";
}
}
#Id
PositionProfile_PK positionProfilePK;
#NotNull
#Column(name="MAX_SPEED")
private Integer max_speed;
#NotNull
#Column(name="WARNING_SPEED")
private Integer warning_speed;
#NotNull
#Column(name="EMERGENCY_SPEED")
private Integer emergency_speed;
#NotNull
#Column(name="DISABLED")
private String disabled;
PositionProfile(){
super();
this.positionProfilePK = new PositionProfile_PK();
this.max_speed = 0;
this.warning_speed = 0;
this.emergency_speed = 0;
this.disabled = " ";
}
}
Controller (summarized for brevity):
PositionProfile positionProfileToUpdate = positionProfile.getPositionProfileByIdPositionAndProfile(pk, profile);
positionProfileToUpdate.setMax_speed(ms);
positionProfile.updatePositionProfile(positionProfileToUpdate);
I've tryed with update() function and saveOrUpdate() but it doesn't work, I don't know what's happening. Session is never closed so the entity is attached. I've checked that values are changed correctly in the object I passed to updatePositionProfile() function, but when merge() it simply does nothing.
Thanks!
if you make flush, the PositionProfile is only for the same session visible.
You must check, if the sessionFactory.getCurrentSession(); working correctly

Spring MVC CrudRepository findByIn

I have a CrudRepository that is supposed to make a query with an array (findByIn). In my repository tests it works, but when I try to use the query in my service, it doesn't work. Could someone explain why it doesn't work? Here is my setup (excluding some code irrelevant to the question)
Database model:
#Entity
#Table(name="Place")
public class Place implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "placeId", nullable = false)
private Long placeId;
#Column(name = "owner", nullable = false)
private String owner;
public Long getPlaceId() {
return placeId;
}
public void setPlaceId(Long placeId) {
this.placeId = placeId;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
Repository:
#Repository
public interface PlaceRepository extends CrudRepository<Place, Long> {
List<Place> findByPlaceIdIn(Long[] placeId);
}
Service (this is the part not working):
#Service
public class PlaceService {
#Autowired
private PlaceRepository placeRepository;
public List<Place> getPlaces(Long[] placeIds) {
return placeRepository.findByPlaceIdIn(placeIds);
}
}
The problem is that in my service placeRepository.findByPlaceIdIn(placeIds) returns 0 objects if placeIds contains more than one item. If placeIds contains just one item, the query works fine. I tried replacing return placeRepository.findByPlaceIdIn(placeIds) with this piece of code that does the query for every array item one by one (this actually works, but I'd like to get the query work as it should):
ArrayList<Place> places = new ArrayList<Place>();
for (Long placeId : placeIds) {
Long[] id = {placeId};
places.addAll(placeRepository.findByPlaceIdIn(id));
}
return places;
I know that the repository should work, because I have a working test for it:
public class PlaceRepositoryTest {
#Autowired
private PlaceRepository repository;
private static Place place;
private static Place place2;
private static Place otherUsersPlace;
#Test
public void testPlacesfindByPlaceIdIn() {
place = new Place();
place.setOwner(USER_ID);
place2 = new Place();
place2.setOwner(USER_ID);
place = repository.save(place);
place2 = repository.save(place2);
Long[] ids = {place.getPlaceId(), place2.getPlaceId()};
assertEquals(repository.findByPlaceIdIn(ids).size(), 2);
}
}
I also have another repository for other model, which also uses findByIn and it works fine. I can't see any relevant difference between the repositories. I thought it might offer some more details to show the working repository, so I included it below:
Database model:
#Entity
#Table(name="LocalDatabaseRow")
#JsonIgnoreProperties(ignoreUnknown=false)
public class LocalDatabaseRow implements Serializable {
public LocalDatabaseRow() {}
public LocalDatabaseRow(RowType rowType) {
this.rowType = rowType;
}
public enum RowType {
TYPE1,
TYPE2
};
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
#JsonProperty("id")
private Long id;
#JsonProperty("rowType")
#Column(name = "rowType")
private RowType rowType;
public Long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public RowType getRowType() {
return rowType;
}
public void setRowType(RowType rowType) {
this.rowType = rowType;
}
}
Repository:
#Repository
public interface LocalDatabaseRowRepository extends CrudRepository<LocalDatabaseRow, Long> {
List<LocalDatabaseRow> findByRowTypeAndUserIdIn(RowType type, String[] userId);
}
try using a list instead :
findByPlaceIdIn(List placeIdList);
You have a typo in your code (the repository declaration in the service):
#Autowired
private placeRepository placeRepository;
Should be:
#Autowired
private PlaceRepository placeRepository;

Play Framework: No #javax.persistence.Id field found in class

I have this Play Model class that I'm trying to modify an object of, and when I want to save it, I get the following exception:
java.lang.RuntimeException: No #javax.persistence.Id field found in class [class models.Contact]
at play.db.ebean.Model._idAccessors(Model.java:39)
at play.db.ebean.Model._getId(Model.java:52)
The class:
#Entity
public class Contact extends Model implements Person {//, Comparable<Contact>{
private Long id;
private Client client;
#Required
private String email;
private String profil_picture;
private Boolean active = new Boolean(true);
private Boolean favorite = new Boolean(false);
#Transient
private Boolean profile_pic_url_init = new Boolean(false);
#Id
#GeneratedValue
public Long getId() {
return id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="client_id")
public Client getClient(){
return client;
}
public void setClient(Client client){
this.client= client;
}
#Column
public Boolean getFavorite() {
return favorite;
}
public void setFavorite(Boolean is_favorite) {
this.favorite = is_favorite;
}
....
}
The code calling the save() method:
List<Contact> contacts_list = current_client.getContacts();
for (Contact c : contacts_list) {
c.setFavorite(false);
c.save();
}
The class actually has an #Id annotation, so any guesses of why this doesn't work? I tried looking it up on google, but couldn't find much about this error. Thanks in advance!
Move #Id annotation to id field instead of its getter.

Categories

Resources