JPA+Hibernate MySql database schema changes does not reflect - java

In my spring web service I am accessing a my sql database with JPA+Hibernate. When I changed my database schema in the database, those changes are not reflecting from my web service.
In more detail I have added a new column formcategoryid to applicationforms table and it is added to JPA annotated class as a field. Now when I execute the query
SELECT x.formid,x.formcategoryid,x.formname FROM com.business.objects.ApplicationForms AS x WHERE x.adminroleid LIKE '3'
It gives the exception,
Caused by: org.hibernate.QueryException: could not resolve property: formcategoryid of: com.business.objects.ApplicationForms
Any idea on this?
UPDATE
My ApplicationForms class is like
package com.business.objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "applicationforms")
public class ApplicationForms {
#Id
#GeneratedValue
private int formid;
private int formcategoryid;
private int adminroleid;
private String formname;
.
.
public int getFormid() {
return formid;
}
public void setFormid(int formid) {
this.formid = formid;
}
public int getFormcategoryid() {
return formcategoryid;
}
public void setFormcategoryid(int formcategoryid) {
this.formcategoryid = formcategoryid;
}
public int getAdminroleid() {
return adminroleid;
}
public void setAdminroleid(int adminroleid) {
this.adminroleid = adminroleid;
}
public String getFormname() {
return formname;
}
public void setFormname(String formname) {
this.formname = formname;
}
}

Related

Spring Boot error: Error creating bean with name 'albumController': Unsatisfied dependency expressed through field 'albumService'

I am new to Spring boot. I am trying to create the below service. Parent class is Artists. Child is Album. I am trying to fetch all the Albums corresponding to particular Artists. While creating custom method in crudRepository I am getting error. Can't able to identify the exact issue, help for the error will be greatly appreciated.
Artists.java (Bean class of Parent)
package com.org.Music_App.Artists;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import com.org.Music_App.Albums.Album;
#Entity
public class Artists {
#Id
private int artists_Id;
private String artists_Name;
private int no_of_Albums;
private String debut_Album;
#OneToMany
#JoinColumn(name = "artists_id")
#Transient
private List<Album> album;
public Artists() {
}
public Artists(int artists_Id, String artists_Name, int no_of_Albums, String debut_Album) {
this.artists_Id = artists_Id;
this.artists_Name = artists_Name;
this.no_of_Albums = no_of_Albums;
this.debut_Album = debut_Album;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
public int getNo_of_Albums() {
return no_of_Albums;
}
public void setNo_of_Albums(int no_of_Albums) {
this.no_of_Albums = no_of_Albums;
}
public String getDebut_Album() {
return debut_Album;
}
public void setDebut_Album(String debut_Album) {
this.debut_Album = debut_Album;
}
public List<Album> getAlbum() {
return album;
}
public void setAlbum(List<Album> album) {
this.album = album;
}
}
Album.java (Bean class of Child)
package com.org.Music_App.Albums;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import com.org.Music_App.Artists.Artists;
#Entity
public class Album {
#Id
private int album_Id;
private int artists_Id;
private String album_Name;
private int no_of_Songs;
private String artists_Name;
public Album()
{
}
public Album(int album_Id, int artists_Id, String album_Name, int no_of_Songs, String artists_Name) {
super();
this.album_Id = album_Id;
this.artists_Id = artists_Id;
this.album_Name = album_Name;
this.no_of_Songs = no_of_Songs;
this.artists_Name = artists_Name;
}
public int getAlbum_Id() {
return album_Id;
}
public void setAlbum_Id(int album_Id) {
this.album_Id = album_Id;
}
public int getArtists_Id() {
return artists_Id;
}
public void setArtists_Id(int artists_Id) {
this.artists_Id = artists_Id;
}
public String getAlbum_Name() {
return album_Name;
}
public void setAlbum_Name(String album_Name) {
this.album_Name = album_Name;
}
public int getNo_of_Songs() {
return no_of_Songs;
}
public void setNo_of_Songs(int no_of_Songs) {
this.no_of_Songs = no_of_Songs;
}
public String getArtists_Name() {
return artists_Name;
}
public void setArtists_Name(String artists_Name) {
this.artists_Name = artists_Name;
}
}
Custom method:
package com.org.Music_App.Repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.org.Music_App.Albums.Album;
import com.org.Music_App.Artists.Artists;
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
Error:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.6.RELEASE.jar:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'albumRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property artists found for type Album!
Can you retry the same code removing all underscores?
Java naming convention use camelcase and Spring assumes conventions in order to wire things properly.
if you have
#Id
private int albumId;
you have:
public int getAlbumId;
public void setAlbumId(int albumId);
etc.
PS: you don't need to define the artistsId property in the Album entity only because there will be an "artistis_id" column in the "album" table.
The AlbumRepository's findByArtists_Id method thinks that it needs to look up data based on artists instead of artist_Id, because it seems to be considering the String after "By" upto the underscore.
Try removing underscore and it may solve your issue.
It seems underscores doesn't work with the entity field names. Here is a similar question, where you can find a detailed answer: Spring-Data-Jpa Repository - Underscore on Entity Column Name
Hope that helps!
You have to define your repository here propertly, add #Repository here
#Repository
public interface AlbumRepository extends CrudRepository<Album, Integer> {
public List<Album> findByArtists_Id(Integer artists_id) ;
}
then it will start working

Join two tables and send as one record

Suppose, that we have such tables:
Table Users
iduser | password
Table Marks
id | iduser | mark | idtest
Table Tests
idtest | title
Query looks like this:
#GET
#Path("/{id}/marks")
#Produces(MediaType.APPLICATION_JSON)
public Object funkcja(#PathParam("id") Integer iduser) {
Query query = em.createQuery("select m,t from Marks m, Tests t where m.idusers=:iduser and m.idtest = t.idtests");
query.setParameter("iduser", id);
List<Object> results = (List<Object>)query.getResultList();
return results;
}
I have entity classes:
Marks , Users, Tests
What I should to do in order to join tables and send JSON type on web service and how to convert JSON to entity class because I would like to show in TableView.
Perhaps there are other simple ways?
Maybe map or JsonObject?
You seem to have multiple questions here; I think you need to break these down into separate questions.
For the "main" question, which is about JPA and how to join the entities, I would do that at the entity level, not at the query level. I.e. I think I would have entity classes like:
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Tests")
public class Test {
#Id
#Column(name="idtest")
private int id ;
private String title ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public boolean equals(Object other) {
if (other instanceof Test) {
return Objects.equals(title, ((Test)other).title);
} else return false ;
}
#Override
public int hashCode() {
return Objects.hash(title);
}
}
and then the Mark entity can use a #ManyToOne annotation to reference the actual Test object (not its id):
import java.util.Objects;
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.Table;
#Entity
#Table(name="Marks")
public class Mark {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id ;
#ManyToOne
#JoinColumn(name="idtest")
private Test test ;
// You probably don't want a reference to User here, as the User class
// encapsulates the password, which you don't want to throw back and
// forward across the network unnecessarily. But if the User class
// instead had a user name etc you wanted, you could use the same
// #ManyToOne technique to reference a User object here if you needed.
#Column(name="iduser")
private int userId ;
private int mark ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public int getMark() {
return mark;
}
public void setMark(int mark) {
this.mark = mark;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Mark) {
Mark other = (Mark)obj ;
return Objects.equals(userId, other.userId)
&& Objects.equals(test, other.test)
&& mark == other.mark ;
} else return false ;
}
#Override
public int hashCode() {
return Objects.hash(userId, test, mark);
}
}
Now your query looks like
TypedQuery<Mark> query = em.createQuery("select m from Mark m where m.userId=:userid");
query.setParameter("userid", iduser);
List<Mark> results = query.getResultList();
and the Mark instances in the list already have all the data you need:
for (Mark mark : results) {
System.out.println(mark.getTest().getTitle() + ": " + mark.getMark());
}
For the remaining questions:
Assuming you have a server set up with a JAX-RS implementation (e.g. Jersey) the code snippet you showed (modified with the new query) should generate JSON output. (You can use a developer tool such as Firefox REST client to view the JSON output by specifying the appropriate URL and request headers, and viewing the response.)
On the client (JavaFX) side you can use Jersey's client library (or maybe Apache HttpComponent library) to create the web requests easily, and a library such as GSON or Jackson for mapping the JSON content you get back to a Java object for display in the TableView.
I recommend trying this and asking specific questions about the remaining pieces if you get stuck.

How to draw database Table items onto a TableView using hibernate

Thank you all with the help so far in my project.
I've been looking at this for most of today, but have been unsuccessful in getting any helpful material.
My project is in Java/ JavaFx, Hibernate and H2. So far I can persist items into the database but I cant figure out how to go about pulling the data onto a TableView. I've gone as far as drawing the data onto System.out.println but nothing more.
These are my classes:
This Class creates the database object, NewBeautifulKiwi:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "KIWI_TABLE")
public class NewBeautifulKiwi implements Serializable {
#Id
#GeneratedValue
private int KiwiId;
private String Kiwi;
public int getKiwiId() {
return KiwiId;
}
public void setKiwiId(int KiwiId) {
this.KiwiId = KiwiId;
}
public String getKiwi() {
return Kiwi;
}
public void setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
}
}
This Class initialises the NewBeautifulKiwi, creating the database Tables and Prints the inserted data to screen:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "KIWI_TABLE")
public class NewBeautifulKiwi implements Serializable {
#Id
#GeneratedValue
private int KiwiId;
private String Kiwi;
public int getKiwiId() {
return KiwiId;
}
public void setKiwiId(int KiwiId) {
this.KiwiId = KiwiId;
}
public String getKiwi() {
return Kiwi;
}
public void setKiwi(String Kiwi) {
this.Kiwi = Kiwi;
}
}
I'd like to have what's printed on screen displayed in a TableView.
Any help would be great. I will be grateful for any help I can get. Thank you in advance.
try this..
i am creating table and column in scene builder
#FXML
private TableView<PoJoName> table;
#FXML
private TableColumn<PoJoName, Integer> col1;
#FXML
private TableColumn<PoJoName, String> col2;
public ObservableList<PoJoName> data;
#FXML
void initialize()
{
col1.setCellValueFactory(new PropertyValueFactory<PoJoName,Integer>("id")); // here id is a variable name which is define in pojo.
col2.setCellValueFactory(new PropertyValueFactory<PoJoName,String>("name"));
data = FXCollections.observableArrayList();
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sess =sf.openSession();
Query qee = sess.createQuery("from PoJoName");
Iterator ite =qee.iterate();
while(ite.hasNext())
{
PoJoName obj = (PoJoName)ite.next();
data.add(obj);
}
table.setItems(data);
}
You need to define a data model for TableView.
Read section "Defining the Data Model" here: http://docs.oracle.com/javafx/2/ui_controls/table-view.htm

#TableGenerator : how to use

i will try to generate the primary keys using table generator. but when i insert the 6 records in my table, the primaryKey table show only one on value. here is the following code
My Entity class
package com.generatorvaluetest.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.TableGenerator;
#Entity
public class Snufu {
private int autoId;
private int identityId;
private int sequenceId;
private int tableId;
private String name;
public int getAutoId() {
return autoId;
}
public void setAutoId(int autoId) {
this.autoId = autoId;
}
public int getIdentityId() {
return identityId;
}
public void setIdentityId(int identityId) {
this.identityId = identityId;
}
public int getSequenceId() {
return sequenceId;
}
public void setSequenceId(int sequenceId) {
this.sequenceId = sequenceId;
}
#Id
#TableGenerator(name="tg" , table="pk_table", pkColumnName="name" ,
valueColumnName="vlaue" , allocationSize=10)
#GeneratedValue(strategy=GenerationType.TABLE , generator="tg")
public int getTableId() {
return tableId;
}
public void setTableId(int tableId) {
this.tableId = tableId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is my main class
package com.generatorvaluetest.main;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import com.generatorvaluetest.domain.Snufu;
import com.generatorvaluetest.util.HibernateUtil;
public class GeneratorValueTest {
public static void main(String[] args) throws HibernateException{
HibernateUtil.recreateDatabase();
Session session = HibernateUtil.beginTransaction();
for(int i = 0 ; i< 5 ; i++){
Snufu snufu = new Snufu();
snufu.setName("jimmy"+i);
session.saveOrUpdate(snufu);
}
new Thread(new Runnable() {
#Override
public void run() {
Session session = HibernateUtil.beginTransaction();
Snufu snufu = new Snufu();
snufu.setName("jimmykalra");
session.saveOrUpdate(snufu);
HibernateUtil.commitTransaction();
}
}).start();
HibernateUtil.commitTransaction();
}
}
in database when i select the values from pk_table the values are
|name | value|
|snuf | 1 |
but in snufu tables there are 6 records
The value for valueColumnName is mispelled as compared with table specified. Also haven't mentioned which row to refer for fetching key, identified by column value(pkColumnValue).
Below is the sample code & can refer TableGenerator documentation, for further reference.
TableGenerator(name="tg" , table="pk_table", pkColumnName="value" ,
valueColumnName="name" , pkColumnValue = "snuf", allocationSize=10)
It can be misleading to see the value 1 in your #TableGenerator table while 6 records have already been inserted in your #Entity table, but the explanation is quite simple.
You've set up your #TableGenerator with an allocationSize=10. What that means is: Hibernate has already pre-allocated IDs from 1 to 9 and once the 9th record is inserted in your #Entity table or you restart your application, the next generated ID will be 10 (pk_table.value * allocationSize). Also, before a row with ID=10 or the next row after application restart is inserted, pk_table.value is incremented by 1, so when this next chunk of 10 is depleted or you restart the application again, ID generation will resume at 20 (2 * 10).
put this code above to your primary key column definition
#TableGenerator(
name="empGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="EMP_ID",
allocationSize=1)
#Id
#GeneratedValue(strategy=TABLE, generator="empGen")
int id;
where you can give any value to recognize a particular table in pkColumnValue field.
for further information on this refer the documentation of #TableGenerator
from below ink
http://docs.oracle.com/javaee/6/api/javax/persistence/TableGenerator.html

JTable TableModel problem in Java

I can show my data in a JTable without a problem, but when I want to filter while my app is running, the JTable is not showing me data changes. I searched for it and found a class named TableModel but I can't write my AbstractTableModel. Can anyone show me how I can do this?
Personelz.Java
package deneme.persistence;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* #author İbrahim AKGÜN
*/
#Entity
#Table(name = "PERSONELZ", catalog = "tksDB", schema = "dbo")
#NamedQueries({#NamedQuery(name = "Personelz.findAll", query = "SELECT p FROM Personelz p"), #NamedQuery(name = "Personelz.findByPersonelıd", query = "SELECT p FROM Personelz p WHERE p.personelıd = :personelıd"), #NamedQuery(name = "Personelz.findByAd", query = "SELECT p FROM Personelz p WHERE p.ad = :ad"), #NamedQuery(name = "Personelz.findBySoyad", query = "SELECT p FROM Personelz p WHERE p.soyad = :soyad")})
public class Personelz implements Serializable {
#Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "PERSONELID", nullable = false )
private Integer personelıd;
#Column(name = "AD", length = 50)
private String ad;
#Column(name = "SOYAD", length = 50)
private String soyad;
#Column(name = "YAS")
private Integer yas;
public Personelz() {
}
public Personelz(Integer personelıd) {
this.personelıd = personelıd;
}
public Integer getPersonelıd() {
return personelıd;
}
public void setPersonelıd(Integer personelıd) {
this.personelıd = personelıd;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
String oldAd = this.ad;
this.ad = ad;
changeSupport.firePropertyChange("ad", oldAd, ad);
}
public String getSoyad() {
return soyad;
}
public void setSoyad(String soyad) {
String oldSoyad = this.soyad;
this.soyad = soyad;
changeSupport.firePropertyChange("soyad", oldSoyad, soyad);
}
public Integer getYas() {
return yas;
}
public void setYas(Integer yas){
this.yas = yas;
}
TABLEMODEL
public class TableModel extends AbstractTableModel {
String[] headers;
List<Personelz> personel;
int row;
int column;
Object[][] per;
/** Creates a new instance of TableModel */
#SuppressWarnings("empty-statement")
public TableModel(List<Personelz> p) {
this.personel = p;
column=2;
row=this.personel.size();
headers=new String[column];
headers[0]="AD";
headers[1]="SOYAD";
per={p.toArray(),p.toArray()};
}
public int getColumnCount()
{
return column;
}
public int getRowCount()
{
return row;
}
public Object getValueAt(int rowIndex, int kolonindex)
{
return per[rowIndex][kolonindex];
}
public String getColumnName(int i)
{
return headers[i];
}
I suggest reading this How to Use Tables (from the Java Tutorials Using Swing Components)
Basically the TableModel has to notify the Table of changed data by firing the appropriate Events. See here
There is a very good library called GlazedLists that makes it a lot simpler to work with lists and tables, including column sorting and row filtering.
Its definitely worth taking a look.
http://publicobject.com/glazedlists/
HTH
You should utilize the TableModelListener interface, which your JTable implements. Once you add your table to your TableModel, call the appropriate fireTableChanged()-type event that AbstractTableModel implements. This should force your JTable to update.
You will still need to implement a method to reset your data in your model when your filter operation returns. it should be in this method that you call your fireTableChanged() event. you also should ensure that you are in the AWT thread when you fire the table changed event.

Categories