它必須有MySQL集羣啓動和運行。爲了簡單起見,組成羣集的所有節點(進程)將與應用程序一起運行在同一臺物理主機上。
這些都是正在使用的MySQL集羣配置文件:
config.ini文件:
[ndbd default]noofreplicas=2
datadir=/home/billy/mysql/my_cluster/data
[ndbd]
hostname=localhost
id=3
[ndbd]
hostname=localhost
id=4
[ndb_mgmd]
id = 1
hostname=localhost
datadir=/home/billy/mysql/my_cluster/data
[mysqld]
hostname=localhost
id=101
[api]
hostname=localhost
的my.cnf:
[mysqld]
ndbcluster
datadir=/home/billy/mysql/my_cluster/data
basedir=/usr/local/mysql
這側重於ClusterJ而不是在運行MySQL集羣;如果您是MySQL Cluster的新手,那麼請在嘗試此操作之前參考運行簡單的羣集。
ClusterJ需要被告知如何連接到我們的MySQL Cluster數據庫;包括連接字符串(管理節點的地址/端口),要使用的數據庫,用戶登錄名以及連接屬性(例如超時值)。如果沒有定義這些參數,那麼ClusterJ將會因運行時異常而失敗。這些信息表示圖3所示的「配置屬性」。這些參數可以在應用程序代碼中進行硬編碼,但更易於創建將由應用程序導入的clusterj.properties文件。這個文件應該存儲在你的應用程序源代碼所在的目錄中。
clusterj.properties:
com.mysql.clusterj.connectstring=localhost:1186
com.mysql.clusterj.database=clusterdb
com.mysql.clusterj.connect.retries=4
com.mysql.clusterj.connect.delay=5
com.mysql.clusterj.connect.verbose=1
com.mysql.clusterj.connect.timeout.before=30
com.mysql.clusterj.connect.timeout.after=20
com.mysql.clusterj.max.transactions=1024
如ClusterJ不會自動創建表,接下來的步驟是創建「clusterdb」數據庫(在clusterj提及。性)和 '僱員' 表:
[[email protected] ~]$ mysql -u root -h 127.0.0.1 -P 3306 -u root
mysql> create database clusterdb;use clusterdb;
mysql> CREATE TABLE employee (
-> id INT NOT NULL PRIMARY KEY,
-> first VARCHAR(64) DEFAULT NULL,
-> last VARCHAR(64) DEFAULT NULL,
-> municipality VARCHAR(64) DEFAULT NULL,
-> started VARCHAR(64) DEFAULT NULL,
-> ended VARCHAR(64) DEFAULT NULL,
-> department INT NOT NULL DEFAULT 1,
-> UNIQUE KEY idx_u_hash (first,last) USING HASH,
-> KEY idx_municipality (municipality)
->) ENGINE=NDBCLUSTER;
下一步是創建註釋的接口:
Employee.java:
import com.mysql.clusterj.annotation.Column;
import com.mysql.clusterj.annotation.Index;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;
@PersistenceCapable(table="employee")
@Index(name="idx_uhash")
public interface Employee {
@PrimaryKey
int getId();
void setId(int id);
String getFirst();
void setFirst(String first);
String getLast();
void setLast(String last);
@Column(name="municipality")
@Index(name="idx_municipality")
String getCity();
void setCity(String city);
String getStarted();
void setStarted(String date);
String getEnded();
void setEnded(String date);
Integer getDepartment();
void setDepartment(Integer department);
}
的表的名稱在註解@PersistenceCapable(table =「employee」)中指定,然後員工表中的每列都有一個在接口中定義的關聯getter和setter方法。默認情況下,接口中的屬性名稱與表中的列名稱相同 - 通過在關聯的getter方法之前明確包含@Column(name =「municipality」)註釋,City屬性的列名已被覆蓋。 @PrimaryKey註釋用於標識其關聯列是表中主鍵的屬性。使用@Index註釋使ClusterJ意識到數據庫中索引的存在。
下一步是編寫我們在這裏逐塊執行的應用程序代碼;其僅包含導入語句,然後第一加載上面所定義的clusterj.properties的內容:
Main.java(部分1):
import com.mysql.clusterj.ClusterJHelper;
import com.mysql.clusterj.SessionFactory;
import com.mysql.clusterj.Session;
import com.mysql.clusterj.Query;
import com.mysql.clusterj.query.QueryBuilder;
import com.mysql.clusterj.query.QueryDomainType;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.*;
import java.util.Properties;
import java.util.List;
public class Main {
public static void main (String[] args) throws java.io.FileNotFoundException,java.io.IOException {
// Load the properties from the clusterj.properties file
File propsFile = new File("clusterj.properties");
InputStream inStream = new FileInputStream(propsFile);
Properties props = new Properties();
props.load(inStream);
//Used later to get userinput
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
下一步是得到一個。辦理從ClusterJHelper類一個SessionFactory,然後使用該工廠創建一個會話(基於clusterj.properties文件導入屬性
Main.java(部分2):
//創建會話(連接到數據庫) SessionFactory factory = ClusterJHelper.getSessionFactory(props); Session session = factory.getSession(); 現在我們有一個會話,可以實例化新的Employee對象,然後將它們保存到數據庫中。在沒有事務begin()或commit()語句的情況下,涉及數據庫的每個操作都被視爲單獨的事務。
Main.java(第3部分):
/
/ Create and initialise an Employee
Employee newEmployee = session.newInstance(Employee.class);
newEmployee.setId(988);
newEmployee.setFirst("John");
newEmployee.setLast("Jones");
newEmployee.setStarted("1 February 2009");
newEmployee.setDepartment(666);
// Write the Employee to the database
session.persist(newEmployee);
此時,一個行將已被添加到「僱員」表。爲了驗證這一點,新的Employee對象被創建並用於使用主鍵998(Id)的值,以讀出的數據從「僱員」表背:
Main.java(部分4):
// Fetch the Employee from the database
Employee theEmployee = session.find(Employee.class, 988);
if (theEmployee == null)
{System.out.println("Could not find employee");}
else
{System.out.println ("ID: " + theEmployee.getId() + "; Name: " +
theEmployee.getFirst() + " " + theEmployee.getLast());
System.out.println ("Location: " + theEmployee.getCity());
System.out.println ("Department: " + theEmployee.getDepartment());
System.out.println ("Started: " + theEmployee.getStarted());
System.out.println ("Left: " + theEmployee.getEnded());
}
這是在這一點上看到的輸出:
ID: 988; Name: John Jones
Location: null
Department: 666
Started: 1 February 2009
Left: null
檢查數據庫之前,我改變了員工 - 當您完成 下一步就是修改這個數據,但它並沒有寫回車它回到數據庫還沒有:
主。爪哇(第5部分):
// Make some changes to the Employee & write back to the database
theEmployee.setDepartment(777);
theEmployee.setCity("London");
System.out.println("Check the database before I change the Employee -
hit return when you are done");
String ignore = br.readLine();
應用程序將暫停在這一點上,給你機會來檢查數據庫,以確認原始數據已被添加爲新行,但更改尚未寫回然後:
mysql> select * from clusterdb.employee;
+-----+-------+-------+--------------+-----------------+-------+------------+
| id | first | last | municipality | started | ended | department |
+-----+-------+-------+--------------+-----------------+-------+------------+
| 988 | John | Jones | NULL | 1 February 2009 | NULL | 666 |
+-----+-------+-------+--------------+-----------------+-------+------------+
點擊返回後,應用程序將繼續並使用自動事務執行更新,將更改寫入表中。
Main.java(第6部分):
session.updatePersistent(theEmployee);
System.out.println("Check the change in the table before I bulk add
Employees - hit return when you are done");
ignore = br.readLine();
應用程序將再次暫停,使我們現在能夠檢查更改已經寫回(堅持)到數據庫:
mysql> select * from clusterdb.employee;
+-----+-------+-------+--------------+-----------------+-------+------------+
| id | first | last | municipality | started | ended | department |
+-----+-------+-------+--------------+-----------------+-------+------------+
| 988 | John | Jones | London | 1 February 2009 | NULL | 777 |
+-----+-------+-------+--------------+-----------------+-------+------------+
然後,應用程序繼續創建並堅持100名新員工。爲了提高性能,單個事務用於所有的變化可以一次寫入到數據庫時提交()語句運行:
Main.java(第7部分):
// Add 100 new Employees - all as part of a single transaction
newEmployee.setFirst("Billy");
newEmployee.setStarted("28 February 2009");
session.currentTransaction().begin();
for (int i=700;i<800;i++) {
newEmployee.setLast("No-Mates"+i);
newEmployee.setId(i+1000);
newEmployee.setDepartment(i);
session.persist(newEmployee);
}
session.currentTransaction().commit();
這100名新員工現在將被堅持到數據庫。下一步是創建並執行一個查詢,該查詢將使用QueryBuilder在部門777中搜索數據庫中的所有員工,並使用該查詢構建將「部門」列與參數進行比較的QueryDomain。創建後,部門參數設置爲777(該查詢可以隨後與不同部門號重複使用)。然後,應用程序運行通過查詢和迭代,並且顯示每個僱員的結果集:
Main.java(部分8):
// Retrieve the set all of Employees in department 777
QueryBuilder builder = session.getQueryBuilder();
QueryDomainType<Employee> domain =
builder.createQueryDefinition(Employee.class);
domain.where(domain.get("department").equal(domain.param(
"department")));
Query<Employee> query = session.createQuery(domain);
query.setParameter("department",777);
List<Employee> results = query.getResultList();
for (Employee deptEmployee: results) {
System.out.println ("ID: " + deptEmployee.getId() + "; Name: " +
deptEmployee.getFirst() + " " + deptEmployee.getLast());
System.out.println ("Location: " + deptEmployee.getCity());
System.out.println ("Department: " + deptEmployee.getDepartment());
System.out.println ("Started: " + deptEmployee.getStarted());
System.out.println ("Left: " + deptEmployee.getEnded());
}
System.out.println("Last chance to check database before emptying table
- hit return when you are done");
ignore = br.readLine();
此時,應用程序將顯示以下並提示用戶允許它繼續:
ID: 988; Name: John Jones
Location: London
Department: 777
Started: 1 February 2009
Left: null
ID: 1777; Name: Billy No-Mates777
Location: null
Department: 777
Started: 28 February 2009
Left: null
我們可以在輸出比較與數據庫上執行一個SQL查詢:
mysql> select * from employee where department=777;
+------+-------+-------------+--------------+------------------+-------+------------+
| id | first | last | municipality | started | ended | department |
+------+-------+-------------+--------------+------------------+-------+------------+
| 988 | John | Jones | London | 1 February 2009 | NULL | 777 |
| 1777 | Billy | No-Mates777 | NULL | 28 February 2009 | NULL | 777 |
+------+-------+-------------+--------------+------------------+-------+------------+
最後,再次按下返回後,應用程序會刪除所有員工:
Main.java(第9部分):
session.deletePersistentAll(Employee.class);
最後檢查,SQL查詢確認所有的行都已從'員工'表中刪除。
mysql> select * from employee;
Empty set (0.00 sec)