JAVA JPA - 正规溶液坚持在项目中的所有对象

时间:2019-01-30 21:35:37

标签: java hibernate jpa persist

我正在它创建新的用户,新闻,各种数据的后端等。

到目前为止,我可以创造并坚持在数据库中的新用户。我认为还将有许多其他实体也具有关系。此时我只看到双向来持久数据:

  • 创建CreateXY,UpdateXY和DeleteXY类
  • 或代码中的每个实体对象persist方法

我认为这是多余的安静一次又一次地写依然存在。有没有一种很好的方法来以一种很好的方式持久化对象?

Main.java

package database;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import backend.User;

public class Main {
    private static final Logger LOGGER = Logger.getLogger("JPA");

    public static void main(String[] args) {
        Main main = new Main();
        main.run();
    }

    public void run() {
        EntityManagerFactory factory = null;
        EntityManager entityManager = null;
        try {
            System.out.println("START");
            factory = Persistence.createEntityManagerFactory("shareiffUnit");
            System.out.println("END");
            entityManager = factory.createEntityManager();
            persistPerson(entityManager);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (entityManager != null) {
                entityManager.close();
            }
            if (factory != null) {
                factory.close();
            }
        }
    }

    private void persistPerson(EntityManager entityManager) {
        EntityTransaction transaction = entityManager.getTransaction();
        try {
            transaction.begin();
            User person = new User();
            person.setName("Homer");
            person.setPassword("Simpson");
            entityManager.persist(person);
            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
        }
    }

}

User.java

package backend;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class User {

    @Id
    @GeneratedValue
    private int id;
    private String name;
    private String password;
    private Boolean isActive = false;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Boolean isActive() {
        return isActive;
    }
    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }

}

2 个答案:

答案 0 :(得分:1)

我倾向于拥有一组类似于经理的类,以及每个经理类的基础。基数是这样的:

public class SomeBaseWritableDAO<T> {
    @PersistenceContext
    private EntityManager entityManager;

    protected EntityManager getEntityManager() {
        return entityManager;
    }

    public void save(T entity) {
        getEntityManager().persist(entity);
    }

    public T update(T entity) {
        return getEntityManager().merge(entity);
    }

    public void delete(T entity) {
        getEntityManager().remove(entity);
    }
}

可以处理任何@Entity类型。然后,如果除了基本的CRUD操作之外,我还需要创建特定于类的管理器:

public class SpecificDAO extends SomeBaseWritableDAO<SpecificEntity> {

    public SpecificEntity findBySomeCode(String inviteCode) {
        final String queryString = "select model from SomeEntity model " +
                "where model.code= :inviteCode";

        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("inviteCode", inviteCode);

        try {
            return (SomeEntity) (query.getSingleResult());
        }
        catch( NoResultException nre ) {
            return null;
        }
    }
}

还有其他方法可以执行此操作,但是此模式在过去一直有效。如果您具有经过适当设计的具有参照完整性的数据库,那么像Eclipse或IntelliJ中那样的良好反向工程工具可以生成一对一和一对多的关系。

答案 1 :(得分:0)

非常感谢。这看起来真的很好。我只是想在我的项目中使用它。看起来到目前为止。我唯一不了解的是承诺在哪里。我以为在坚持之后

Main.java

public class Main {
     public static void main(String[] args) {

        /*
         * just create a user to persist
         */     
        User aUser = new User();
        aUser.setActive(true);
        aUser.setName("Hans");
        aUser.setPassword("Müller");        
        GenericDao dao = new GenericDao();        
        dao.update(aUser);     
        System.out.println("PERSIST?");
    }
}

DaoInterface.java

public interface IGenericDao<E> {
    void create(E entity);
    E read(Integer id);
    void update(E entity);
    void delete(E entity);
}

Dao.java

public class GenericDao<E> implements IGenericDao<E> {

    @PersistenceContext
    private static EntityManager entityManager;

    private EntityManager getEntityManager() {
        return entityManager;
    }

    public void create(E entity) {
        getEntityManager().persist(entity);
    }

    public E read(Integer id) {
        // TODO Auto-generated method stub
        return null;
    }

    public void update(E entity) {
        // TODO Auto-generated method stub

    }

    public void delete(E entity) {
        // TODO Auto-generated method stub

    }
}

提前谢谢