Close

Spring Framework - JPA Examples

Spring Framework 

import com.logicbig.example.Customer;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

public class JpaCustomerDao implements Dao<Customer> {
@Autowired
private EntityManager entityManager;


@PostConstruct
private void postConstruct() {
//just populate some test data if it's first time
try {
if (loadAll().size() == 0) {
DataUtil.createTestData().forEach(this::saveOrUpdate);
}
} catch (Exception e) {
DataUtil.createTestData().forEach(this::saveOrUpdate);
}
}


@Override
public void saveOrUpdate(Customer customer) {
entityManager.getTransaction().begin();
entityManager.persist(customer);
entityManager.getTransaction().commit();
}


@Override
public Customer load(long id) {
Query query = entityManager.createQuery(
"SELECT t FROM Customer where t.id = :id");
query.setParameter("id", id);
List resultList = query.getResultList();
if (resultList.size() > 0) {
return (Customer) resultList.get(0);
}
return null;
}

@Override
public List<Customer> loadAll() {
Query query = entityManager.createQuery(
"SELECT t FROM Customer t");
return query.getResultList();
}
}




import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Customer {

@Id
@GeneratedValue
private long customerId;

private String name;
private String address;
private String phone;
//other details

public long getCustomerId() {
return customerId;
}

public void setCustomerId(long customerId) {
this.customerId = customerId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Customer customer = (Customer) o;
return customerId == customer.customerId;
}

@Override
public int hashCode() {
return (int) (customerId ^ (customerId >>> 32));
}

@Override
public String toString() {
return "Customer{" +
"customerId='" + customerId + '\'' +
", name='" + name + '\'' +
", address='" + address + '\'' +
", phone='" + phone + '\'' +
'}';
}
}




See Also