2017年5月19日 星期五

Java 7 新的 try-with-resources 語法(Auto Source release )

出處: OSChina : https://www.oschina.net/question/12_10706
作者:@红薯

Java 7 build 105 版本開始,Java 7 的編譯器和運行環境已支援新的 try-with-resources 語法,稱為 ARM (Automatic Resource Management) ,自動資源管理。
新的語句支援包括流以及任何可關閉的資源,例如,一般我們會編寫如下代碼來釋放資源:

private static void customBufferStreamCopy(File source, File target) {
    InputStream fis = null;
    OutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
 
        byte[] buf = new byte[8192];
 
        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(fis);
        close(fos);
    }
}
 
private static void close(Closeable closable) {
    if (closable != null) {
        try {
            closable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


而使用 try-with-resources 語法來簡化如下:
private static void customBufferStreamCopy(File source, File target) {
    try (InputStream fis = new FileInputStream(source);
        OutputStream fos = new FileOutputStream(target)){
 
        byte[] buf = new byte[8192];
 
        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}


or

public static void customBufferStreamCopy(String[] args) throws Exception{
 @Cleanup InputStream in = new FileInputStream(args[0]);
 @Cleanup OutputStream out = new FileOutputStream(args[1]);
 byte[] buf = new byte[8192];       
        int i;  
        while ((i = in.read(buf)) != -1) {  
            out.write(buf, 0, i);  
        }  
}


2017年5月7日 星期日

一對多 Hibernate4 One To Many Annotation (By MS SQL)

參考文章:  http://viralpatel.net/blogs/hibernate-one-to-many-annotation-tutorial/

 One To Many : 一個部門 (department) 有多個員工(employee )
 Many To One : 多個員工(employee )屬於一個部門

一對多情況時,必須於  一 與 多的二方設定以上關聯

在 MS SQL 執行 CREATE TABLE
CREATE TABLE dbo.department (
department_id  INT IDENTITY(1,1)PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL DEFAULT '0'
);

CREATE TABLE dbo.employee (
employee_id INT IDENTITY(1,1)PRIMARY KEY,
firstname VARCHAR(50) NULL DEFAULT NULL,
lastname VARCHAR(50) NULL DEFAULT NULL,
birth_date DATE NULL DEFAULT NULL,
cell_phone VARCHAR(15) NULL DEFAULT NULL,
department_id INT FOREIGN KEY REFERENCES dbo.department(department_id)
);

Employee.java
import java.sql.Date;
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="EMPLOYEE")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="employee_id")
private Integer employeeId;

@Column(name="firstname")
private String firstname;

@Column(name="lastname")
private String lastname;

@Column(name="birth_date")
private Date birthDate;

@Column(name="cell_phone")
private String cellphone;

@ManyToOne
@JoinColumn(name="department_id")
private Department department;

public Employee() {

}

public Employee(String firstname, String lastname, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = new Date(System.currentTimeMillis());
this.cellphone = phone;
}

public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}

public Integer getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}

public String getFirstname() {
return firstname;
}

public String getLastname() {
return lastname;
}

public Date getBirthDate() {
return birthDate;
}

public String getCellphone() {
return cellphone;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
}

Department.java
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="DEPARTMENT")
public class Department {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="DEPARTMENT_ID")
private Integer departmentId;

@Column(name="DEPT_NAME")
private String departmentName;

@OneToMany(mappedBy="department")
private Set<Employee> employees;

public Integer getDepartmentId() {
return departmentId;
}

public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}

public String getDepartmentName() {
return departmentName;
}

public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}

public Set<Employee> getEmployees() {
return employees;
}

public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}

For TEST

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

public static void main(String[] args) {

SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();

Department department = new Department();
department.setDepartmentName("Sales");
session.save(department);

Employee emp1 = new Employee("Nina", "Mayers", "111");
Employee emp2 = new Employee("Tony", "Almeida", "222");

emp1.setDepartment(department);
emp2.setDepartment(department);

session.save(emp1);
session.save(emp2);

session.getTransaction().commit();
session.close();
}
}






Java 不同編碼字串, 其字串長度大小計算

以 Java 開發專案, 在 DAO 寫入資料庫時, 常遇到JAVA 字串與資料庫編碼不一致, 有時會產生字串過長,導致無法寫入資料庫的情況. 這時就要在入庫前, 先驗證 JAVA 編碼字串是否超出資料庫欄位長度 JAVA 依 不同編碼, 其長度是不一樣的 如: ...