使用 Hibernate 将数据从一张表复制到另一张表

时间:2021-03-11 02:19:18

标签: java hibernate

import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

public int insert() {
    StringBuilder buf = new StringBuilder();
    buf.append("INSERT INTO EmployeeGroup SELECT * FROM Employee");
    Query query = getEntityManager().createQuery(buf.toString());
    return query.executeUpdate();
}

出现错误“INSERT INTO EmployeeGroup SELECT * FROM Employee”

引起:org.hibernate.hql.internal.ast.QuerySyntaxException:期望打开,在第 1 行第 36 列附近找到“SELECT”[INSERT INTO EmployeeGroup SELECT * FROM Employee] 在 org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:131) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:93) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1836) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final] 在 org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328) ~[hibernate-entitymanager-4.3.10.Final.jar:4.3.10.Final] ...省略了 30 个常用帧

1 个答案:

答案 0 :(得分:0)

使用 createNativeQuery 使其工作并给出表名而不是实体名(用实际表名代替实体名替换 EmployeeGroup 和 Employee)。