Java Database Connectivity
java.sql.Connection
java.sql.Statement
java.sql.PreparedStatement
java.sql.CallableStatement
java.sql.ResultSet
DriverManager.registerDriver(new org.postgresql.Driver());
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/db_name",
"user", "password");
Statement stmt = conn.createStatement();
stmt.executeUpdate(
"INSERT INTO student( login, name ) VALUES ( 'some_login', 'my name' ) " );
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(
rs.getRow() + ". " +
rs.getString("login") + " " +
rs.getString("name"));
}
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM student" );
while ( rs.next() ) {
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
System.out.println("COLUMN " + i + " = " + rs.getObject(i));
}
}
PreparedStatement ps =
conn.prepareStatement("SELECT login " +
" FROM users WHERE name = ?");
ps.setString(1, "Kent");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
try(Connection conn = DriverManager.getConnection(
"jdbc:...", "user", "password")) {
try(Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("...")) {
...
}
}
conn.setAutoCommit(false);
try {
...
conn.commit();
} catch (Throwable e) {
try { conn.rollback(); } catch (Throwable e) {
logger.warn("Could not rollback transaction", e);
}
throw e;
}
String sql = "insert into employee (login, name) values (?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
for (Student st: students) {
ps.setString(1, st.getLogin());
ps.setString(2, st.getName());
ps.addBatch();
}
ps.executeBatch();
@Entity
public class User {
String login;
String name;
School school;
...
}
@Entity
public class Student {
@Id
String login;
String name;
School school;
...
}
@Entity
@Table(name = "STUDENT")
public class Student {
@Id
@Column(name=”STUDENT_LOGIN”, length = 32)
String login;
@Column(name=”FULL_NAME”)
String name;
School school;
@Entity
public class Student {
...
@Temporal(TemporalType.TIMESTAMP)
Date creationDate;
...
}
@Entity
public class Student {
...
@ManyToOne(name=”SCHOOL_ID”, fetch = FetchType.LAZY)
School school;
@ManyToOne(name=”Man_ID”, fetch = FetchType.EAGER)
Man father;
...
}
@PersistenceUnit
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();
или
@PersistenceContext
EntityManager em;
<?xml version="1.0" encoding="UTF-8" ?>
<persistence>
<persistence-unit name="my-pu">
<description>My Persistence Unit</description>
<provider>
org.hibernate.jpa.HibernatePersistenceProvider
</provider>
<class>sample.Student</class>
<class>sample.School</class>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/somedb"/>
<property name="javax.persistence.jdbc.user"
value="name"/>
<property name="javax.persistence.jdbc.password"
value="pass"/>
</properties>
</persistence-unit>
</persistence>
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void insert() {
School school = new School(1, "Школа №1");
Student student = new Student("pupkin", "Вася пупкин", school);
entityManager.persist(school);
entityManager.persist(student);
}
@PersistenceContext
private EntityManager entityManager;
@Transactional
public Student find(String login) {
return entityManager.find(Student.class, "pupkin");
}
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void delete(String login) {
Student student = find(login);
entityManager.remove(student);
}
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void update(String login) {
Student student = find(login);
student.setName("Петров");
entityManager.merge(student);
}
@Transactional
public List<Student> listStudents(String name) {
List<Student> students = entityManager
.createQuery("from " + Student.class.getName()
+ " where name like :name", Student.class)
.setParameter("name", "%" + name + "%")
.getResultList();
return students;
}
@Transactional
public List<String> listLogins(String name) {
List<String> students = entityManager
.createNativeQuery("SELECT login FROM students "
+ " WHERE name like :name")
.setParameter("name", "%" + name + "%")
.getResultList();
return students;
}
@Transactional
public List<Student> listStudentsByName(String name) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Student> query = builder.createQuery(Student.class);
Root<Student> from = query.from(Student.class);
query.where(builder.equal(from.get("name"), name));
return entityManager.createQuery(query).getResultList();
}
@Entity
@NamedQuery(name="Country.findAll",
query="SELECT c FROM Country c")
public class Country {
...
}
TypedQuery<Country> query =
em.createNamedQuery("Country.findAll", Country.class);
List<Country> results = query.getResultList();
@Entity
@Cacheable
class Student {
...
}
T findOne(ID primaryKey);
Iterable<T> findAll();
Long count();
boolean exists(ID primaryKey);
T save(T entity);
void delete(T entity);
...
userRepository.findAll();
userRepository.findOne(id);
userRepository.count();
userRepository.save(user);
userRepository.exists(userId);
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
...
Long countByFirstName(String firstName);
List<User> findByUserTypeOrderByFirstNameDesc(UserTypeuserType);
User findByFirstNameAndLastName(String firstName, String lastName);
User findByFirstNameAndLastNameAllIgnoreCase(
String firstName, String lastName);
List<Task> findByAssignedToUserFirstNameAndAssignedToUserLastName(
String firstName, String lastName);
find...By..., count...By..., delete...By...
...Distinct...
...And..., ...Or...
...Equals..., (...Is...), ...Not..., ...In..., ...NotIn...,
...Like..., ...NotLike..., ...StartingWith...,
...EndingWith..., ...Containing...
...Between..., ...LessThan..., ...LessThenEqual...,
...GreaterThan..., ...GreaterThanEqual...
...After..., ...Before...
...IsNull..., ...isNotNull, (...notNull...), True, False
...IgnoreCase..., ...AllIgnoreCase...
...OrderBy...Asc, ...OrderBy...Desc
...first10...
Pageable
List<Task> findFirst3ByCreatedByUser(User user, Sort sort);
@Query("select t from Task t where t.number IN (:numbers)")
List<Task> findByNumberIn(
@Param("numbers") Collection<String> numbers);
public interface CustomTaskRepository {
String findTaskNumberByTitleFragment(String fragment);
}
@Repository
public class TaskRepositoryImpl implements CustomTaskRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public String findTaskNumberByTitleFragment(String fragment) {
Query query = entityManager.createNativeQuery(...);
query.setParameter("fragment", "%" + fragment + "%");
return (String) query.getSingleResult();
}
}