Database Connectivity
JDBC
// 1. Import the package
import java.sql.*
// 2a. Load driver (driver for whichever database you are using)
// 2b. Register driver
Class.forName("com.mysql.jdbc.Driver");
// 3. Establish Connection
Connection con = DriverManager.getConnection("URL", "username", "password");
// 4. Create the statement
Statement st = con.createStatement();
// 5. Execute the query
ResultSet rs = st.executeQuery(query);
//OR
int count = st.executeUpdate(query);
// 6. Process Result
rs.next();
String s = rs.getString(columnNumber);
// 7. Close
st.close();
con.close();
Use PreparedStatement for user input
Use PreparedStatement instead of Statement to give user input in queries
query - (?,?) // question marks for parameters you want to take as user input in the query
Prepared Statement st = con.prepareStatement(query);
st.setInt(1, input1);
st.setString(2, input2);
JPA
Annotations
Entity and Mapping Annotations
@Entity
: Marks a class as a JPA entity.@Id
: Primary Key within entity@GeneratedValue
: Specified how primary key is generated- Strategies:
AUTO
,IDENTITY
,SEQUENCE
,TABLE
- Strategies:
- Optional Annotations to specify corresponding DB names for accurately mapping the entity. By default, names are directly mapped from the object.
@Table
: Specifies DB table - default = entity name@Column
- Relationships
@JoinColumn
: Foreign Key@JoinTable
: Defines join table for many-to-many- Cardinality
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany