By GokiSoft.com|
20:15 21/03/2020|
Java Web + EJB (EAD)
Share Code- Chữa bài tập quản lý công ty - SessionBean EJB
Hướng dẫn chữa bài tập
[EAD][EJB] Assignment viết chương trình quản lý công ty
CompanyLibs Project
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="CompanyLibsPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>entities.Company</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/company"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
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.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author DiepTV
*/
@Entity
@Table(name = "company")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Company.findAll", query = "SELECT c FROM Company c"),
@NamedQuery(name = "Company.findById", query = "SELECT c FROM Company c WHERE c.id = :id"),
@NamedQuery(name = "Company.findByName", query = "SELECT c FROM Company c WHERE c.name = :name"),
@NamedQuery(name = "Company.findByCompanyKey", query = "SELECT c FROM Company c WHERE c.companyKey = :companyKey"),
@NamedQuery(name = "Company.findByAddress", query = "SELECT c FROM Company c WHERE c.address = :address"),
@NamedQuery(name = "Company.findByEnabled", query = "SELECT c FROM Company c WHERE c.enabled = :enabled")})
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "name")
private String name;
@Column(name = "company_key")
private String companyKey;
@Lob
@Column(name = "description")
private String description;
@Column(name = "address")
private String address;
@Column(name = "enabled")
private Integer enabled;
public Company() {
}
public Company(Integer id) {
this.id = id;
}
public Company(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompanyKey() {
return companyKey;
}
public void setCompanyKey(String companyKey) {
this.companyKey = companyKey;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getEnabled() {
return enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Company)) {
return false;
}
Company other = (Company) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entities.Company[ id=" + id + " ]";
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entities.Company;
import java.util.List;
import javax.ejb.Remote;
/**
*
* @author DiepTV
*/
@Remote
public interface CompanySessionBeanRemote {
List<Company> findAll();
Company find(int id);
void insert(Company company);
void update(Company company);
}
CompanyEJB
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entities.Company;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
/**
*
* @author DiepTV
*/
@Stateless
public class CompanySessionBean implements CompanySessionBeanRemote {
@Override
public List<Company> findAll() {
//Tao ket noi toi database
EntityManagerFactory factory = Persistence.createEntityManagerFactory("CompanyLibsPU");
EntityManager em = factory.createEntityManager();
Query q = em.createNamedQuery("Company.findAll", Company.class);
return q.getResultList();
}
@Override
public Company find(int id) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("CompanyLibsPU");
EntityManager em = factory.createEntityManager();
return em.find(Company.class, id);
}
@Override
public void insert(Company company) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("CompanyLibsPU");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist(company);
em.getTransaction().commit();
}
@Override
public void update(Company company) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("CompanyLibsPU");
EntityManager em = factory.createEntityManager();
Company cmpFind = em.find(Company.class, company.getId());
em.getTransaction().begin();
cmpFind.setAddress(company.getAddress());
cmpFind.setCompanyKey(company.getCompanyKey());
cmpFind.setDescription(company.getDescription());
cmpFind.setEnabled(company.getEnabled());
cmpFind.setName(company.getName());
em.getTransaction().commit();
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
CompanyClient/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package company;
import entities.Company;
import java.util.List;
import javax.ejb.EJB;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import session.CompanySessionBeanRemote;
/**
*
* @author DiepTV
*/
public class MainFrame extends javax.swing.JFrame {
@EJB
private static CompanySessionBeanRemote companySessionBean;
DefaultTableModel tableModel;
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
tableModel = (DefaultTableModel) tblCompany.getModel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtName = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtCompanyKey = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
cbEnabled = new javax.swing.JCheckBox();
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txtDescription = new javax.swing.JTextArea();
btnShowAll = new javax.swing.JButton();
btnFind = new javax.swing.JButton();
btnUpdate = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
tblCompany = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Company Information"));
jLabel1.setText("ID: ");
jLabel2.setText("Name: ");
jLabel3.setText("Company Key: ");
jLabel4.setText("Address: ");
cbEnabled.setText("Enabled");
jLabel5.setText("Description:");
txtDescription.setColumns(20);
txtDescription.setRows(5);
jScrollPane1.setViewportView(txtDescription);
btnShowAll.setText("Show All");
btnShowAll.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnShowAllActionPerformed(evt);
}
});
btnFind.setText("Find");
btnFind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindActionPerformed(evt);
}
});
btnUpdate.setText("Update");
btnUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(89, 89, 89)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnShowAll))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
.addComponent(txtCompanyKey, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
.addComponent(cbEnabled)
.addComponent(jScrollPane1))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnFind)
.addComponent(btnUpdate))))))
.addContainerGap(20, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnShowAll))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtCompanyKey, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnFind))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnUpdate))
.addGap(18, 18, 18)
.addComponent(cbEnabled)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel5))
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
tblCompany.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Name", "Company Key", "Address", "Enabled", "Description"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(tblCompany);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnShowAllActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
List<Company> list = companySessionBean.findAll();
tableModel.setRowCount(0);
for (Company company : list) {
tableModel.addRow(new Object[]{company.getId(), company.getName(), company.getCompanyKey(),
company.getAddress(), company.getEnabled(), company.getDescription()});
}
}
private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(txtId.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(this, "Nhap ID can tim kiem");
return;
}
int id = Integer.parseInt(txtId.getText());
Company company = companySessionBean.find(id);
if(company != null) {
txtName.setText(company.getName());
txtCompanyKey.setText(company.getCompanyKey());
txtAddress.setText(company.getAddress());
if(company.getEnabled() == 1) {
cbEnabled.setSelected(true);
} else {
cbEnabled.setSelected(false);
}
txtDescription.setText(company.getDescription());
} else {
JOptionPane.showMessageDialog(this, "Khong tim thay thong tin cty vs ID nhap vao");
}
}
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Company company = new Company();
company.setId(Integer.parseInt(txtId.getText()));
company.setName(txtName.getText());
company.setAddress(txtAddress.getText());
company.setCompanyKey(txtCompanyKey.getText());
if(cbEnabled.isSelected()) {
company.setEnabled(1);
} else {
company.setEnabled(0);
}
company.setDescription(txtDescription.getText());
companySessionBean.update(company);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnFind;
private javax.swing.JButton btnShowAll;
private javax.swing.JButton btnUpdate;
private javax.swing.JCheckBox cbEnabled;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tblCompany;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtCompanyKey;
private javax.swing.JTextArea txtDescription;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtName;
// End of variables declaration
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)