Profesora + Anotaciones mias.

This commit is contained in:
2026-03-08 20:07:17 +01:00
commit 1236e1ff4a
30 changed files with 1924 additions and 0 deletions

View File

@@ -0,0 +1,107 @@
package com.example.hibernate.model;
// Generated 19 feb 2026, 19:19:40 by Hibernate Tools 6.6.0.Final
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import static jakarta.persistence.GenerationType.IDENTITY;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
// import jakarta.persistence.Temporal;
// import jakarta.persistence.TemporalType;
import java.math.BigDecimal;
//import java.sql.Timestamp;
import java.time.LocalDateTime;
/**
* AccMovement generated by hbm2java
*/
@Entity
@Table(name="acc_movement"
)
public class AccMovement implements java.io.Serializable {
@Override
public String toString() {
return "AccMovement [accountMovId=" + accountMovId + ", amount=" + amount + ", datetime=" + datetime + "]";
}
private Integer accountMovId;
private Account accountByAccountDestId;
private Account accountByAccountOriginId;
private BigDecimal amount;
private LocalDateTime datetime;
public AccMovement() {
}
public AccMovement(Account accountByAccountDestId, Account accountByAccountOriginId, BigDecimal amount, LocalDateTime datetime) {
this.accountByAccountDestId = accountByAccountDestId;
this.accountByAccountOriginId = accountByAccountOriginId;
this.amount = amount;
this.datetime = datetime;
}
@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="ACCOUNT_MOV_ID", unique=true, nullable=false)
public Integer getAccountMovId() {
return this.accountMovId;
}
public void setAccountMovId(Integer accountMovId) {
this.accountMovId = accountMovId;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ACCOUNT_DEST_ID", nullable=false)
public Account getAccountByAccountDestId() {
return this.accountByAccountDestId;
}
public void setAccountByAccountDestId(Account accountByAccountDestId) {
this.accountByAccountDestId = accountByAccountDestId;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ACCOUNT_ORIGIN_ID", nullable=false)
public Account getAccountByAccountOriginId() {
return this.accountByAccountOriginId;
}
public void setAccountByAccountOriginId(Account accountByAccountOriginId) {
this.accountByAccountOriginId = accountByAccountOriginId;
}
@Column(name="AMOUNT", nullable=false, precision=19, scale=4)
public BigDecimal getAmount() {
return this.amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
// @Temporal(TemporalType.TIMESTAMP)
@Column(name="DATETIME", nullable=false, length=19)
public LocalDateTime getDatetime() {
return this.datetime;
}
public void setDatetime(LocalDateTime datetime) {
this.datetime = datetime;
}
}

View File

@@ -0,0 +1,112 @@
package com.example.hibernate.model;
// Generated 19 feb 2026, 19:19:40 by Hibernate Tools 6.6.0.Final
import static jakarta.persistence.GenerationType.IDENTITY;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
/**
* Account generated by hbm2java
*/
@Entity
@Table(name="account"
)
public class Account implements java.io.Serializable {
@Override
public String toString() {
return "Account [accountno=" + accountno + ", amount=" + amount + "]";
}
private Integer accountno;
private Emp emp;
private BigDecimal amount;
private Set<AccMovement> accMovementsForAccountDestId = new HashSet<AccMovement>(0);
private Set<AccMovement> accMovementsForAccountOriginId = new HashSet<AccMovement>(0);
public Account() {
}
public Account(Emp emp, BigDecimal amount) {
this.emp = emp;
this.amount = amount;
}
public Account(Emp emp, BigDecimal amount, Set<AccMovement> accMovementsForAccountDestId, Set<AccMovement> accMovementsForAccountOriginId) {
this.emp = emp;
this.amount = amount;
this.accMovementsForAccountDestId = accMovementsForAccountDestId;
this.accMovementsForAccountOriginId = accMovementsForAccountOriginId;
}
@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="ACCOUNTNO", unique=true, nullable=false)
public Integer getAccountno() {
return this.accountno;
}
public void setAccountno(Integer accountno) {
this.accountno = accountno;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="EMPNO", nullable=false)
public Emp getEmp() {
return this.emp;
}
public void setEmp(Emp emp) {
this.emp = emp;
}
@Column(name="AMOUNT", nullable=false, precision=19, scale=4)
public BigDecimal getAmount() {
return this.amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="accountByAccountDestId", cascade = CascadeType.REMOVE)
public Set<AccMovement> getAccMovementsForAccountDestId() {
return this.accMovementsForAccountDestId;
}
public void setAccMovementsForAccountDestId(Set<AccMovement> accMovementsForAccountDestId) {
this.accMovementsForAccountDestId = accMovementsForAccountDestId;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="accountByAccountOriginId", cascade = CascadeType.REMOVE)
public Set<AccMovement> getAccMovementsForAccountOriginId() {
return this.accMovementsForAccountOriginId;
}
public void setAccMovementsForAccountOriginId(Set<AccMovement> accMovementsForAccountOriginId) {
this.accMovementsForAccountOriginId = accMovementsForAccountOriginId;
}
}

View File

@@ -0,0 +1,85 @@
package com.example.hibernate.model;
// Generated 19 feb 2026, 19:19:40 by Hibernate Tools 6.6.0.Final
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import static jakarta.persistence.GenerationType.IDENTITY;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import java.util.HashSet;
import java.util.Set;
/**
* Dept generated by hbm2java
*/
@Entity
@Table(name="dept"
)
public class Dept implements java.io.Serializable {
private Integer deptno;
private String dname;
private String loc;
private Set<Emp> emps = new HashSet<Emp>(0);
public Dept() {
}
public Dept(String dname, String loc, Set<Emp> emps) {
this.dname = dname;
this.loc = loc;
this.emps = emps;
}
@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="DEPTNO", unique=true, nullable=false)
public Integer getDeptno() {
return this.deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
@Column(name="DNAME", length=20)
public String getDname() {
return this.dname;
}
public void setDname(String dname) {
this.dname = dname;
}
@Column(name="LOC", length=20)
public String getLoc() {
return this.loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="dept")
public Set<Emp> getEmps() {
return this.emps;
}
public void setEmps(Set<Emp> emps) {
this.emps = emps;
}
}

View File

@@ -0,0 +1,183 @@
package com.example.hibernate.model;
// Generated 19 feb 2026, 19:19:40 by Hibernate Tools 6.6.0.Final
import static jakarta.persistence.GenerationType.IDENTITY;
// import jakarta.persistence.Temporal;
// import jakarta.persistence.TemporalType;
import java.math.BigDecimal;
import java.time.LocalDate;
//import java.sql.Date;
import java.util.HashSet;
import java.util.Set;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
/**
* Emp generated by hbm2java
*/
@Entity
@Table(name="emp"
)
public class Emp implements java.io.Serializable {
private Integer empno;
private Dept dept;
private Emp jefe;
private String ename;
private String job;
private LocalDate hiredate;
private BigDecimal sal;
private BigDecimal comm;
private Set<Account> accounts = new HashSet<Account>(0);
private Set<Project> projects = new HashSet<Project>(0);
private Set<Emp> emps = new HashSet<Emp>(0);
public Emp() {
}
public Emp(Dept dept, Emp emp, String ename, String job, LocalDate hiredate, BigDecimal sal, BigDecimal comm, Set<Account> accounts, Set<Project> projects, Set<Emp> emps) {
this.dept = dept;
this.jefe = emp;
this.ename = ename;
this.job = job;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.accounts = accounts;
this.projects = projects;
this.emps = emps;
}
@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="EMPNO", unique=true, nullable=false)
public Integer getEmpno() {
return this.empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="DEPTNO")
public Dept getDept() {
return this.dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="MGR")
public Emp getJefe() {
return this.jefe;
}
public void setJefe(Emp emp) {
this.jefe = emp;
}
@Column(name="ENAME", length=20)
public String getEname() {
return this.ename;
}
public void setEname(String ename) {
this.ename = ename;
}
@Column(name="JOB", length=20)
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
//@Temporal(TemporalType.DATE)
@Column(name="HIREDATE", length=10)
public LocalDate getHiredate() {
return this.hiredate;
}
public void setHiredate(LocalDate hiredate) {
this.hiredate = hiredate;
}
@Column(name="SAL", precision=15, scale=2)
public BigDecimal getSal() {
return this.sal;
}
public void setSal(BigDecimal sal) {
this.sal = sal;
}
@Column(name="COMM", precision=15, scale=2)
public BigDecimal getComm() {
return this.comm;
}
public void setComm(BigDecimal comm) {
this.comm = comm;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="emp")
public Set<Account> getAccounts() {
return this.accounts;
}
public void setAccounts(Set<Account> accounts) {
this.accounts = accounts;
}
@ManyToMany(fetch=FetchType.LAZY, mappedBy = "emps")
// @JoinTable(name="project_emp", catalog="empresa", joinColumns = {
// @JoinColumn(name="EMPNO", nullable=false, updatable=false) }, inverseJoinColumns = {
// @JoinColumn(name="PROJECTNO", nullable=false, updatable=false) })
public Set<Project> getProjects() {
return this.projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="jefe")
public Set<Emp> getEmps() {
return this.emps;
}
public void setEmps(Set<Emp> emps) {
this.emps = emps;
}
}

View File

@@ -0,0 +1,82 @@
package com.example.hibernate.model;
// Generated 19 feb 2026, 19:19:40 by Hibernate Tools 6.6.0.Final
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import static jakarta.persistence.GenerationType.IDENTITY;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import java.util.HashSet;
import java.util.Set;
/**
* Project generated by hbm2java
*/
@Entity
@Table(name="project"
)
public class Project implements java.io.Serializable {
private Integer projno;
private String projname;
private Set<Emp> emps = new HashSet<Emp>(0);
public Project() {
}
public Project(String projname) {
this.projname = projname;
}
public Project(String projname, Set<Emp> emps) {
this.projname = projname;
this.emps = emps;
}
@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="PROJNO", unique=true, nullable=false)
public Integer getProjno() {
return this.projno;
}
public void setProjno(Integer projno) {
this.projno = projno;
}
@Column(name="PROJNAME", nullable=false, length=50)
public String getProjname() {
return this.projname;
}
public void setProjname(String projname) {
this.projname = projname;
}
@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="project_emp", catalog="empresa", joinColumns = {
@JoinColumn(name="PROJECTNO", nullable=false) }, inverseJoinColumns = {
@JoinColumn(name="EMPNO", nullable=false) })
public Set<Emp> getEmps() {
return this.emps;
}
public void setEmps(Set<Emp> emps) {
this.emps = emps;
}
}

View File

@@ -0,0 +1,14 @@
package com.example.hibernate.model.dao;
import org.hibernate.SessionFactory;
import com.example.hibernate.model.AccMovement;
import com.example.hibernate.model.util.GenericDaoHibernate;
public class AccMovementDaoHibernate extends GenericDaoHibernate<AccMovement, Integer> implements IAccMovementDao {
public AccMovementDaoHibernate(SessionFactory sessionFactory) {
super(sessionFactory);
}
}

View File

@@ -0,0 +1,21 @@
package com.example.hibernate.model.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import com.example.hibernate.model.Account;
import com.example.hibernate.model.util.GenericDaoHibernate;
public class AccountDaoHibernate extends GenericDaoHibernate<Account, Integer> implements IAccountDao {
public AccountDaoHibernate(SessionFactory sessionFactory) {
super(sessionFactory);
}
@Override
public List< Account> getAccountsByEmpno(Integer empno) {
return getSession().createSelectionQuery("from Account where emp.empno = :empno", Account.class)
.setParameter("empno", empno).getResultList();
}
}

View File

@@ -0,0 +1,14 @@
package com.example.hibernate.model.dao;
import org.hibernate.SessionFactory;
import com.example.hibernate.model.Emp;
import com.example.hibernate.model.util.GenericDaoHibernate;
public class EmpleadoDaoHibernate extends GenericDaoHibernate<Emp, Integer> implements IEmpleadoDao {
public EmpleadoDaoHibernate(SessionFactory sessionFactory) {
super(sessionFactory);
}
}

View File

@@ -0,0 +1,8 @@
package com.example.hibernate.model.dao;
import com.example.hibernate.model.AccMovement;
import com.example.hibernate.model.util.IGenericDao;
public interface IAccMovementDao extends IGenericDao<AccMovement, Integer> {
}

View File

@@ -0,0 +1,11 @@
package com.example.hibernate.model.dao;
import java.util.List;
import com.example.hibernate.model.Account;
import com.example.hibernate.model.util.IGenericDao;
public interface IAccountDao extends IGenericDao<Account, Integer> {
public List<Account> getAccountsByEmpno(Integer empno);
}

View File

@@ -0,0 +1,8 @@
package com.example.hibernate.model.dao;
import com.example.hibernate.model.Emp;
import com.example.hibernate.model.util.IGenericDao;
public interface IEmpleadoDao extends IGenericDao<Emp, Integer> {
}

View File

@@ -0,0 +1 @@
# En esta carpeta deberíais añadir las clases e interfaces DAO

View File

@@ -0,0 +1,79 @@
package com.example.hibernate.model.servicio;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import com.example.hibernate.model.AccMovement;
import com.example.hibernate.model.Account;
import com.example.hibernate.model.dao.IAccMovementDao;
import com.example.hibernate.model.dao.IAccountDao;
import com.example.hibernate.model.util.TransactionManager;
public class AccountServicio implements IAccountServicio {
private IAccountDao accountDao;
private IAccMovementDao accmovDao;
private TransactionManager transactionManager;
public AccountServicio(IAccMovementDao accmovDao, IAccountDao accountDao, TransactionManager transactionManager) {
this.accountDao = accountDao;
this.accmovDao = accmovDao;
this.transactionManager = transactionManager;
}
public List<Account> getAccountsByEmpno(Integer empno) {
return transactionManager.ejecutar(() -> accountDao.getAccountsByEmpno(empno));
}
@Override
public AccMovement autoTransferir(Integer accountno, double diferencia) {
return transactionManager.ejecutar(() -> {
Account account = accountDao.find(accountno);
double saldoAnterior = account.getAmount().doubleValue();
double saldoNuevo = saldoAnterior + diferencia;
account.setAmount(BigDecimal.valueOf(saldoNuevo));
accountDao.update(account);
AccMovement accmov = new AccMovement();
accmov.setAccountByAccountDestId(account);
accmov.setAccountByAccountOriginId(account);
accmov.setAmount(BigDecimal.valueOf(diferencia));
accmov.setDatetime(LocalDateTime.now());
accmovDao.create(accmov);
return accmov;
});
}
@Override
public void crear(Account account) {
transactionManager.ejecutar(() -> {
accountDao.create(account);
return null;
});
}
@Override
public void update(Account account) {
transactionManager.ejecutar(() -> {
accountDao.update(account);
return null;
});
}
@Override
public void delete(Integer accountno) {
transactionManager.ejecutar(() -> {
// for (AccMovement accmov : accmovDao.findAll()) {
// if (accmov.getAccountByAccountDestId().getAccountno().equals(accountno) ||
// accmov.getAccountByAccountOriginId().getAccountno().equals(accountno)) {
// accmovDao.remove(accmov.getAccountMovId());
// }
// }
accountDao.remove(accountno);
return null;
});
}
}

View File

@@ -0,0 +1,28 @@
package com.example.hibernate.model.servicio;
import com.example.hibernate.model.Emp;
import com.example.hibernate.model.dao.EmpleadoDaoHibernate;
import com.example.hibernate.model.dao.IEmpleadoDao;
import com.example.hibernate.model.util.TransactionManager;
import com.example.hibernate.model.util.exceptions.InstanceNotFoundException;
public class EmpleadoServicio implements IEmpleadoServicio {
private IEmpleadoDao empleadoDao;
private TransactionManager transactionManager;
public EmpleadoServicio(IEmpleadoDao empleadoDao, TransactionManager transactionManager) {
this.empleadoDao = empleadoDao;
this.transactionManager = transactionManager;
}
public Emp find(Integer empno) throws InstanceNotFoundException {
return transactionManager.ejecutar(() -> empleadoDao.find(empno));
}
}

View File

@@ -0,0 +1,20 @@
package com.example.hibernate.model.servicio;
import java.util.List;
import com.example.hibernate.model.AccMovement;
import com.example.hibernate.model.Account;
public interface IAccountServicio {
public AccMovement autoTransferir(Integer accountno, double diferencia);
public void crear(Account account);
public void update(Account account);
public List<Account> getAccountsByEmpno(Integer empno);
public void delete(Integer accountno);
}

View File

@@ -0,0 +1,10 @@
package com.example.hibernate.model.servicio;
import com.example.hibernate.model.Emp;
import com.example.hibernate.model.util.exceptions.InstanceNotFoundException;
public interface IEmpleadoServicio {
public Emp find(Integer empno) throws InstanceNotFoundException;
}

View File

@@ -0,0 +1,89 @@
package com.example.hibernate.model.util;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.example.hibernate.model.util.exceptions.InstanceNotFoundException;
/**
* Implementación xenérica do DAO en Hibernate.
*
* @author maria
*/
public class GenericDaoHibernate<E, PK extends Serializable> implements IGenericDao<E, PK> {
private final Class<E> entityClass;
private final SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public GenericDaoHibernate(SessionFactory sessionFactory) {
// getClass(): accedemos a la clase de la instancia que extienda esta clase
// (será ProfesorDaoHibernate u XDaoHibernate)
// .getGenericSuperclass(): obtenemos el tipo de la clase madre directa:
// GenericDaoHibernate En el caso de que sea una clase parametrizada (con
// Generics),devuelve el tipo del parámetro de tipo E: ParameterizedType:
// https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getGenericSuperclass--
// .getActualTypeArguments(): devuelve un array de los tipos de los argumentos
// que se le pasan al tipo parametrizado <E, PK>
// finalmente obtenemos el nombre del tipo parametrizado: <E> que será
// Profesor
this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public void create(E entity) {
Session session = getSession();
session.persist(entity);
}
@Override
public E update(E entity) {
Session session = getSession();
return session.merge(entity);
}
@Override
public boolean exists(PK id) {
Session session = getSession();
return session.get(entityClass, id) != null;
}
@Override
public E find(PK id) throws InstanceNotFoundException {
Session session = getSession();
E entity = session.get(entityClass, id);
if (entity == null) {
throw new InstanceNotFoundException(id, entityClass.getName());
}
return entity;
}
@Override
public void remove(PK id) throws InstanceNotFoundException {
Session session = getSession();
E entity = session.get(entityClass, id);
if (entity == null) {
throw new InstanceNotFoundException(id, entityClass.getName());
}
session.remove(entity);
}
@Override
public List<E> findAll() {
Session session = getSession();
return session.createSelectionQuery("SELECT c FROM " + entityClass.getName() + " c", entityClass)
.getResultList();
}
}

View File

@@ -0,0 +1,67 @@
package com.example.hibernate.model.util;
import java.io.Serializable;
import java.util.List;
import com.example.hibernate.model.util.exceptions.InstanceNotFoundException;
/**
*
* @author maria
* @param <E>
*/
public interface IGenericDao<E, PK extends Serializable> {
// Usamos un tipo genérico para indicar que la interfaz IGenericDao tendrá un
// parámetro de cualquier tipo (clases del modelo), salvo tipos primitivos
// https://docs.oracle.com/javase/tutorial/java/generics/types.html
//Se usa un segundo tipo parametrizado para la clave primaria
/***
* Guarda una entidad en el sistema de persistencia
*
* @param entity
* @return la entidad con la clave primaria asignada
*/
public void create(E entity);
/***
* Busca en el sistema de persistencia una entidad por su clave primaria
*
* @param id
* @return la entidad si la encuentra
* @throws InstanceNotFoundException si no encuentra la entidad
*/
public E find(PK id) throws InstanceNotFoundException;
/***
* Comprueba si existe la entidad con ese id como clave primaria
*
* @param id
* @return true si se ha encontrado, false en caso contrario.
*/
public boolean exists(PK id);
/***
* Elimina una entidad del sistema de persistencia
*
* @param id clave primaria para encontrar la entidad
* @throws InstanceNotFoundException si no encuentra la entidad
*/
public void remove(PK id) throws InstanceNotFoundException;
/**
* Obtiene una lista de todas las entidades en el sistema persistente
*
* @return
*/
public List<E> findAll();
/**
* Actualiza una entidad del sistema de persistencia
* @param entidad a actualizar
* @return entidad actualizada y persistente
*/
public E update(E entity);
}

View File

@@ -0,0 +1,6 @@
package com.example.hibernate.model.util;
@FunctionalInterface
public interface OperacionHibernate<R> {
public R ejecutar() throws Exception;
}

View File

@@ -0,0 +1,28 @@
package com.example.hibernate.model.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class TransactionManager {
private final SessionFactory sessionFactory;
public TransactionManager(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public <R> R ejecutar(OperacionHibernate<R> operacion) {
Transaction tx = null;
try {
Session session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
R resultado = operacion.ejecutar();
tx.commit();
return resultado;
} catch (Exception e) {
if (tx != null) tx.rollback();
throw new RuntimeException("Error en la transacción", e);
}
}
}

View File

@@ -0,0 +1,35 @@
package com.example.hibernate.model.util.exceptions;
/**
*
* @author maria
*/
public class InstanceNotFoundException extends Exception {
private Object key;
private String className;
private static final String DEFAULT_MSG = "Instance not found";
public InstanceNotFoundException( Object key,
String className) {
super(DEFAULT_MSG + " (key = '" + key + "' - className = '"
+ className + "')");
this.key = key;
this.className = className;
}
public Object getKey() {
return key;
}
public String getClassName() {
return className;
}
}