How to bind JTable with database using Hibernate - java

Hi,
I have database in MySql and want to get my table to be bind with Swing JTable.
Now my DAO class retrieves data from my table and stores it into java.util.List.
What approaches I could use to bind db table with JTable?

As you have data fetched from Database wrapped by DAO, using DAO put those information in relevant row/column of your JTable.
Here are SO Question and answer for your requirement. Hope they will help you.
Populate JTable Using List
Java GUI aplication, load data to Jtable from a list<objects>
How to add data to JTable created in design mode?
Other Resources.
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Session sesion = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = sesion.beginTransaction();
List today = sesion.createQuery("FROM class WHERE something").list();
for (Iterator iterator = today.iterator(); iterator.hasNext();){
Salidas Sal = (Salidas) iterator.next();
tablemodel.addRow(new Object[]{
//`enter code here`columns
Sal.getId(),
Sal.getUsuarios().getNombre().toString(),
Sal.getCantidadPrestada(),
Sal.getCantidadPedida(),
Sal.getFechaSalida()});
}
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
sesion.close();
}

Related

mySQL adding duplicate data to TableView in JavaFX

I want to add data from mySql database to a table view using observable list as well, using a "Refresh button" that adds new rows to the tableview everytime it is clicked. Here is the code:
public void refreshPage(){
Order curOrder = ordersList.getSelectionModel().getSelectedItem();
ordersList.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
String query = "SELECT orderID, orderStatus, orderTotalCost FROM ORDERS";
try {
DatabaseConnection DBconn = new DatabaseConnection();
connection = DBconn.getDatabaseLink();
// connection = DatabaseConnection.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
while (resultSet.next()){
Order newOrder = new Order(resultSet.getString("orderID"), resultSet.getString("orderStatus"), resultSet.getDouble("orderTotalCost"));
orders.add(newOrder);
}
ordersList.setItems(orders);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
refreshPage() is linked to a button on the javaFX stage.
ordersList is the tableView and orders is the observable list.
However, the issue is that when clicking the refresh page button multiple times, it adds the same rows from the data base over and over, I only want it to add unique values to the tableview from the database.
You can use ObservableSet to avoid adding duplicated items.
Create set:
ObservableSet<Order> observableSet = FXCollections.observableSet();
Add new items to set (duplicates will be skipped):
observableSet.add(newOrder);

JTable not showing added entries in database

Im creating an inventory system for our project in school but I stumbled across a problem, I have two forms, when I click the add button in my firstform called mainform, a new form will show the addjframe form, I then put entries, but when I click the add button in the addjframe form the data is in my ms-access database, but my jtable is blank
I tried making my table public static so that it can be called on my second form
heres the code for for my table on the mainform
public static void AddRowToJTable(Object[] dataRow)
{
DefaultTableModel dtm ;
dtm= (DefaultTableModel)jTable1.getModel();
dtm.addRow(dataRow);
dtm.setRowCount(0);
}
heres the code for my add button on the Addjframe form/second form
private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {
String title = txttitle.getText();
String author = txtauthor.getText();
String date = txtdate.getText();
String genre = txtgenre.getText();
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection con = DriverManager.getConnection("jdbc:ucanaccess://D:/elibrary1.accdb");
Statement st = con.createStatement();
st.execute("INSERT INTO libtable(Title,Author,Dateadded,Genre) VALUES ('"+title+"','"+author+"','"+date+"','"+genre+"')");
String sql = "Select * from libtable";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
mainform.AddRowToJTable(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)});
}
}
catch (Exception e) {
System.out.print(e.getMessage());
}
}
It should show the entries on my jtable i dont know whats wrong with my code, ive been stuck on this for days, I dont receive any error messages, because the entries are being put in my ms-access database its just that it doesnt show on my jtable
Any help would be appreciated!
here's my first form the table is not showing anything when i click add on my second form
this is my second form to add data in the database
here is my ms-access database showing my recently entered data at the bottom

Updated Datastore without using Key#id by using java

I have the sample code below which updates the records based on the key id but i need a sample script which updates the DS values based on other columns rather than using key i also tried using query but couldn't find a solution.
boolean markDone(long id) {
Transaction transaction = datastore.newTransaction();
try {
Entity task = transaction.get(keyFactory.newKey(id));
if (task != null) {
transaction.put(Entity.newBuilder(task).set("done", true).build());
}
transaction.commit();
return task != null;
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
}
This page has a number of query examples.
If you want the query to be part of a transaction, it will need to be an ancestor query.

How to set TableModel as DataSource in an empty iReport (NetBeans 7.1)

This is my first time to create a report using iReport plugin in Netbeans 7.1. I have all the records that I need (records were stored in a TableModel) and I want it to set as the datasource to an empty report.
Here's what I did so far:
1.) I have a TableModel from a ResultSet. (fields: StudentID, FullName, SectionName)
private TableModel ConvertResultSetToTableModel(ResultSet rs)
{
TableModel tb;
... // codes here
return tb;
}
2.) I added an EmptyReport on my project. The reason why it's empty is because I do not want iReport to connect to my database server.
3.) This is my sample report (no elegant design yet). How can I bind or fill the fields of the TableModel (fields: StudentID, FullName, SectionName) to the TextField of the iReport ($F{StudentID}, $F{FullName}, $F{SectionName})? And how can I also directly set the $F{CourseName} TextField from a local string variable?
I hope I made everything clear here. Please help. Thank you.
This would be the answer to your question
Jasper reports provides implementation that makes the task of generating reports from tabular formats simple in Swing
applications. In this demonstrations, we will be using Jasper reports 3.6.1, Netbeans 6.1 and Ireport 3.6.1.
Try this code
private void generateReports(String name, Map param)
{
try
{
String source = "C:/sabonay/jasperreports/" + name + ".jrxml";
if (new File(source).exists() == false)
{
xputils.showMessage("Please go to setting and Choose report Source");
return;
}
JasperReport jasperReport = JasperCompileManager.compileReport(source);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JRTableModelDataSource(tbProducts.getModel()));
JasperViewer.viewReport(jasperPrint, false);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("reports Error " + e.toString());
}
}
For more Info Visit this link...

Is it possible to detach Hibernate entity, so that changes to object are not automatically saved to database?

I have Hibernate entity that I have to convert to JSON, and I have to translate some values in entity, but when I translate values, these values are instantly saved to database, but I don't want to save these changes to database. Is there any workaround for this problem?
You can detach an entity by calling Session.evict().
Other options are create a defensive copy of your entity before translation of values, or use a DTO instead of the entity in that code. I think these options are more elegant since they don't couple conversion to JSON and persistence layer.
I am also converting hibernate entities to JSON.
The bad thing when you close the session you cannot lazy load objects. For this reason you can use
hSession.setDefaultReadOnly(true);
and close the session after when you're done with the JSON.
You can also avoid that your entities are attached to the Hibernate Session by using a StatelessSession:
StatelessSession session = sessionFactory.openStatelessSession();
instead of
Session session = sessionFactory.getCurrentSession();
Note that you must take care yourself of closing the StatelessSession, unlike the regular Hibernate Session:
session.close(); // do this after you are done with the session
Another difference compared to the regular Session is that a StatelessSession can not fetch collections. I see it's main purpose for data-fetching-only SQLQuery stuff.
You can read more about the different session types here:
http://www.interviewadda.com/difference-between-getcurrentsession-opensession-and-openstatelesssession/
Close the Session. That will detach your entity for you, and no modifications will be flushed. If that's not possible, look into disabling autoFlush...but that's a whole other can of worms. The easiest is to close the Session and be done with it!
public static <E> E deepClone(E e) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo;
try {
oo = new ObjectOutputStream(bo);
oo.writeObject(e);
} catch (IOException ex) {
ex.printStackTrace();
}
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi;
try {
oi = new ObjectInputStream(bi);
return (E) (oi.readObject());
} catch (IOException ex) {
ex.printStackTrace();
return null;
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
return null;
}
}
first: deepClone the session pojo
second: alter fields
then: do whatever you want to do
In my case I just flushed and cleared the session.
session.flush();
session.clear();

Categories