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
Related
i need to update tow columns inside my table (Job this table is joint with two other tables employees and job-history)one of them is the primary key, but i get error, if someone can help.
package com.touati.org.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the jobs database table.
*
*/
#Entity
#Table(name="jobs")
#NamedQuery(name="Job.findAll", query="SELECT j FROM Job j")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="JOB_ID")
private String jobId;
#Column(name="JOB_TITLE")
private String jobTitle;
#Column(name="MAX_SALARY")
private BigDecimal maxSalary;
#Column(name="MIN_SALARY")
private BigDecimal minSalary;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="job")
private List<Employee> employees;
//bi-directional many-to-one association to JobHistory
#OneToMany(mappedBy="job")
private List<JobHistory> jobHistories;
public Job() {
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getMaxSalary() {
return this.maxSalary;
}
public void setMaxSalary(BigDecimal maxSalary) {
this.maxSalary = maxSalary;
}
public BigDecimal getMinSalary() {
return this.minSalary;
}
public void setMinSalary(BigDecimal minSalary) {
this.minSalary = minSalary;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setJob(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setJob(null);
return employee;
}
public List<JobHistory> getJobHistories() {
return this.jobHistories;
}
public void setJobHistories(List<JobHistory> jobHistories) {
this.jobHistories = jobHistories;
}
public JobHistory addJobHistory(JobHistory jobHistory) {
getJobHistories().add(jobHistory);
jobHistory.setJob(this);
return jobHistory;
}
public JobHistory removeJobHistory(JobHistory jobHistory) {
getJobHistories().remove(jobHistory);
jobHistory.setJob(null);
return jobHistory;
}
}
my controller: here when i try to look for all job in the data base it works fine, also if i try to update juste the title of the job it works fine to but in case that i try to set a new primary key for the job table it gives me error here my controller.
package com.touati.org.model;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
#Controller // This means that this class is a Controller
#RequestMapping(path="/project") // This means URL's start with /demo (after Application path)
public class MainController {
#GetMapping(path="/job")
public #ResponseBody Iterable<Job> getAllJob() {
// This returns a JSON or XML with the users
return jobRepository.findAll();
}
#GetMapping(path="/job/{jobId}")
public #ResponseBody String getJob(#PathVariable String jobId) {
Job job = jobRepository.findOne(jobId);
try {
job.setJobTitle("manager");
job.setJobId("test1");
jobRepository.save(job);
}
catch (Exception ex) {
return "Error updating the job: " + ex.toString();
}
return "Job succesfully updated!";
}
}
i got this error,
Error updating the user: org.springframework.orm.jpa.JpaSystemException: identifier of an instance of com.touati.org.model.Job was altered from test to test1; nested exception is org.hibernate.HibernateException: identifier of an instance of com.touati.org.model.Job was altered from test to test1
Thank you for your help.
Primary key should never be changed. If you need to change primary key it means your design is bad. If you need to change JOB_ID often then create another column for your primary key like ID. Another possibility is to copy all attributes and create new record with new JOB_ID and then remove old one.
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.
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;
}
}
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
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.