Showing posts with label Java DB. Show all posts
Showing posts with label Java DB. Show all posts

Wednesday, 19 May 2010

Composite Primary Keys for JPA Entities

When the primary key of a JPA entity is composed from more than one attribute it is necessary to define a class corresponding to the primary key.

The JPA entity will use the @IdClass annotation to specify the name of the class corresponding to the composite primary key.

In the class corresponding to the JPA entity, the attributes included in the primary key will be marked with the @Id annotation.

Example using a compound primary key in JPA

1.Create and populate a table to be used by the example.

ij> CREATE TABLE Grades(
> studentID INTEGER NOT NULL,
> cursID INTEGER NOT NULL,
> semestrul1 INTEGER,
> semestrul2 INTEGER,
> laborator INTEGER,
> CONSTRAINT pk_SidCid PRIMARY KEY(studentID,cursID));
0 rows inserted/updated/deleted
...
ij> INSERT INTO Grades VALUES
> (1,1,9,10,10);
1 row inserted/updated/deleted
...
 ij> SELECT * FROM Grades;
STUDENTID  |CURSID     |SEMESTRUL1 |SEMESTRUL2 |LABORATOR
-----------------------------------------------------------
1          |1          |9          |10         |10
2          |1          |8          |7           |8
3          |1          |10         |10        |10
28 rows selected

2.Define the JPA entity

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Column;
import javax.persistence.NamedQuery;
import java.io.Serializable;

@Entity
@Table(name="GRADES")
@IdClass(GradesPK.class)
@NamedQuery(name="Grades.forOneStudent",
query="select o from Grades o where o.studentId=:param")

public class Grades implements Serializable{

@Id
@Column(name="STUDENTID", nullable=false)
private int studentId;

@Id
@Column(name="CURSID", nullable=false)
private int cursId;

@Column(name="SEMESTRUL1")
private int semestrul1;

...
}

3.Define the class corresponding to the primary key.

Make sure that the names and types of the fields are the same with those in the entity bean!

import java.io.Serializable;

public class GradesPK implements Serializable{

public int studentId;
public int cursId;

public GradesPK(){
//constructor public fara parametri
}

public GradesPK(int studentId, int cursId){
this.studentId=studentId;
this.cursId=cursId;
}

public int hashCode(){
return super.hashCode();
}

public boolean equals(Object other){

if(!(other instanceof GradesPK)){
return false;}

GradesPK celalalt = (GradesPK)other;

return(celalalt.studentId==studentId
       &&
      celalalt.cursId==cursId);
}
}

4.Define a method in a session bean to use for testing a query.

public List getGradesforOneStudent(int idStud){
List note = (List)em.createNamedQuery("Grades.forOneStudent").
            setParameter("param",idStud).getResultList();

return note;
}


5.Write a test client to call the method.
 
import javax.naming.InitialContext;
import java.util.List;
import java.util.ListIterator;
...

public class Client1{
public static void main(String[] args) throws Exception
{
    InitialContext ctx = new InitialContext();
    FatadaCursuri beanInstance = (FatadaCursuri)
                                      ctx.lookup(FatadaCursuri.class.getName());

    List grades = beanInstance.getGradesforOneStudent(2);
    ListIterator listIterator2 = grades.listIterator();
    System.out.println("Notele studentului cu studentId=2");
    while(listIterator2.hasNext()){
    Grades linie = (Grades)listIterator2.next();
    System.out.print("ID Curs:"+linie.citesteCursId());
    System.out.print(" Nota 1:"+linie.citesteSemestrul1());
    System.out.print(" Nota 2:"+linie.citesteSemestrul2());
    System.out.println(" Nota lab.:"+linie.citesteLaborator());   
    }
}
}

Wednesday, 14 April 2010

Definirea unei surse de date Java DB in GlassFish V3

Crearea şi distrugerea conexiunilor la o bază de date poate fi costisitoare, ceea ce justifică menţinerea unui "rezervor de conexiuni'' (connection pool), o mulţime de conexiuni reutilizabile, pentru o anumită bază de date, pregătite în prealabil şi administrate de către serverul de aplicaţii. Definiţia unei surse de date în GlassFish trebuie să fie precedată de definiţia rezervorului de conexiuni folosit de aceasta. Am definit rezervorul de conexiuni şi sursa de date folosind consola grafică pentru administrare a serverului, aşa cum se vede în figurile următoare.

 Pentru ca definiţia unui rezervor de conexiuni pe o bază de date Java DB să fie completă trebuie definite şi următoarele proprietăţi: DatabaseName, User, Password, PortNumber, ServerName. Mai jos este specificat ca exemplu un set de valori pentru aceste proprietăţi.

DatabaseName = C:\Sun\SDK\javaDB\bin\student
User = profesor
Password = parolaprofesor
PortNumber = 1527
ServerName = localhost

Sunday, 11 April 2010

O aplicaţie simplă cu Java DB

import java.sql.*;

public class Student {

public static void main(String[] args) {

Connection dbConnection = null;     
String dbUrl =
"jdbc:derby:C:\\Sun\\SDK\\javadb\\bin\\student;"+
"user=profesor;password=parolaprofesor";

try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//incarca driver JDBC pt JavaDB
}

catch(ClassNotFoundException e) {
e.printStackTrace(); 
System.out.println("Eroare incarcare driver!\n" + e);
}

try{
dbConnection=DriverManager.getConnection(dbUrl);
Statement stmt= dbConnection.createStatement();
ResultSet  rs =
stmt.executeQuery(
" SELECT * FROM student");

while (rs.next()) {
System.out.println (
rs.getString ("nume") + "," +
rs.getString ("prenume") + "," +
rs.getString ("email"));
}
stmt.close();
}

catch(SQLException e) {
e.printStackTrace();
}
}
}
Programul se execută precizând în linia de comandă pentru maşina virtuală Java calea către driverul Java DB pentru SQL(derby.jar):

java -classpath .;C:\Sun\SDK\javadb\lib\derby.jar Student

Wednesday, 7 April 2010

Introducere în Java DB

Java DB este o versiune a sistemului Derby(Apache) pentru baze de date. Această versiune este dezvoltată în întregime în tehnologie Java şi este în prezent "împachetată" în serverul de aplicaţii GlassFish.

Execuţia comenzilor SQL

Instrumentul pe care îl avem la dispoziţie pentru execuţia comenzilor SQL în Java DB, atât a comenzilor de interogare cât şi a celor de creare a tabelelor şi manipulare a datelor, se numeşte ij. Interfaţa utilizatorului cu ij este linia de comandă.

Pe calculatorul meu, ij se găseşte în directorul C:\Sun\SDK\javadb\bin. Pentru a deschide o conexiune la baza de date, a crea o tabelă şi a insera valori în aceasta am executat următoarele comenzi:

C:\Sun\SDK\javadb\bin>ij

ij>connect 'jdbc:derby:student;
create=true; user=profesor;
password = parolaprofesor'
as my_connection;

ij>CREATE TABLE t1(
nume VARCHAR(30),
varsta INTEGER);

ij>INSERT INTO t1 VALUES
('Cristina',31);

ij>SELECT * FROM t1;

ij>exit;

C:\Sun\SDK\javadb\bin>