java - Hibernate 不生成更新的 sql 代码

标签 java hibernate spring-mvc

我有带有 Hibernate 的 Spring MVC 应用程序。早些时候,我有一个类,它与每个实体的 session (数据库)一起使用,一切都运行良好。现在,我有了抽象 Dao 类,每个实体都由一个类继承。当我想在数据库中插入新数据时,一切正常。但是当我想要更新数据时,它们到达 Controller (我可以在控制台中打印它们),但 Hibernate 不会生成用于更新的 sql 代码。我打开 Hibernate 的属性来显示 sql,我看到 hibernate 生成了除 UPDATE 之外的所有 sql 查询。抽象类中的所有方法都有效,除了更新方法

一件有趣的事情是我在控制台中没有遇到任何错误。

这是交叉点类

@Entity
@Table(name = "intersections")
public class Intersection implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "symbol")
    private Integer symbol;
    @Size(max = 256)
    @Column(name = "title")
    private String title;

    @OneToMany(mappedBy = "intersection",cascade = CascadeType.ALL)
    private List<Access> accessList;

访问类

@Entity
@Table(name = "accesses")
public class Access implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "symbol")
    private Integer symbol;
    @Size(max = 50)
    @Column(name = "title")
    private String title;

    @JoinColumn(name = "intersection", referencedColumnName = "id")
    @ManyToOne(cascade = CascadeType.ALL)
    private Intersection intersection;

抽象类

public abstract class AbstractDao<T, I, A, P, ID extends Serializable> implements DaoInterface<T, I, A, P, ID>{

    @Autowired
    private SessionFactory sessionFactory;
    private Class<T> classType;

    public AbstractDao(){
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        this.classType = (Class<T>)type.getActualTypeArguments()[0];
    }

    @Override
    public void insert(T t) {
        Session session = sessionFactory.getCurrentSession();
        session.save(t);
    }

    @Override
    public void update(T t) {
        Session session = sessionFactory.getCurrentSession();
        session.update(t);
    }

    @Override
    public List<T> getAll() {
        Session session = sessionFactory.getCurrentSession();
        Criteria c = session.createCriteria(classType);
        c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        c.addOrder(Order.asc("symbol"));
        List<T> list = c.list();
        return list;
    }

    @Override
    public T getById(ID id) {
        Session session = sessionFactory.getCurrentSession();
        T a = (T)session.get(classType, id);
        return a;
    }

    @Override
    public List<T> getByIntersection(I i) {
        Session session = sessionFactory.getCurrentSession();
        Criteria c = session.createCriteria(classType);
        c.add(Restrictions.eq("intersection", i));
        c.addOrder(Order.asc("symbol"));
        List<T> list = c.list();
        return list;
    }

    @Override
    public List<T> getByAccess(A a) {
        Session session = sessionFactory.getCurrentSession();
        Criteria c = session.createCriteria(classType);
        c.add(Restrictions.eq("access", a));
        c.addOrder(Order.asc("symbol"));
        List<T> list = c.list();
        return list;
    }

    @Override
    public List<T> getByPole(P p) {
        Session session = sessionFactory.getCurrentSession();
        Criteria c = session.createCriteria(classType);
        c.add(Restrictions.eq("pole", p));
        c.addOrder(Order.asc("symbol"));
        List<T> list = c.list();
        return list;
    }

AccessDao

@Transactional(propagation = Propagation.REQUIRED, readOnly = false) 
public class AccessDao extends AbstractDao<Access, Intersection, Access, Pole, Integer>{

}

Controller 中的方法

@RequestMapping(value = "/access", method = RequestMethod.POST)
    public String accessUpdate(
            @RequestParam Integer idInt,
            @RequestParam Integer idAccess,
            @RequestParam String symbol,
            @RequestParam String title,
            ModelMap model){
        String naslov = "Ažuriranje prilaza";
        model.addAttribute("naslov", naslov);
        List<Intersection> intersections = intersectionDao.getAll();
        model.addAttribute("intersections", intersections);

        Intersection i = intersectionDao.getById(idInt);
        Access a = (Access) accessDao.getById(idAccess);
        a.setIntersection(i);
        a.setSymbol(Integer.parseInt(symbol));
        a.setTitle(title);
        accessDao.update(a);

        return "accessupdate";
    }

编辑:web.xml, Spring 配置

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

    <!-- Context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/applicationContext.xml,
            /WEB-INF/spring/database.xml,
            /WEB-INF/spring/spring-security.xml
        </param-value>
    </context-param>

    <!-- Listeners -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Dispatcher Servlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
            <max-file-size>10485760</max-file-size>
            <max-request-size>20971520</max-request-size>
            <file-size-threshold>5242880</file-size-threshold>
        </multipart-config>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Filters -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
     <filter-name>hibernateFilter</filter-name>
     <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
     <init-param>
         <param-name>sessionFactoryBeanName</param-name>
         <param-value>sessionFactory</param-value> 
     </init-param>
    </filter>

    <filter-mapping>
     <filter-name>hibernateFilter</filter-name>
     <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

</web-app>

applicationContext.xml

<?xml version='1.0' encoding='UTF-8' ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/p http://www.springframework.org/schema/p/spring-p-4.0.xsd" >

    <context:component-scan base-package="com.intersections.controller" />
    <context:component-scan base-package="com.intersections.model" />
    <context:component-scan base-package="com.intersections.dao" />
    <mvc:annotation-driven />
    <mvc:resources mapping="/assets/**" location="/assets/" />
    <mvc:resources mapping="/pdf/**" location="/pdf/" />

</beans>

数据库.xml

<?xml version='1.0' encoding='UTF-8' ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.url}"
        p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" /> 
        <property name="annotatedClasses">
        <list>
            <value>com.intersections.model.Intersection</value>
            <value>com.intersections.model.Access</value>
            <value>com.intersections.model.Pole</value>
            <value>com.intersections.model.TrafficSignalController</value>
            <value>com.intersections.model.Detector</value>
            <value>com.intersections.model.SignalHead</value>
            <value>com.intersections.model.PedestrianPushButton</value>
            <value>com.intersections.model.PedestrianDisplay</value>
            <value>com.intersections.model.User</value>
            <value>com.intersections.model.Rank</value>
       </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property> 
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <bean id="accessDao" class="com.intersections.dao.AccessDao" />
    <bean id="detectorDao" class="com.intersections.dao.DetectorDao"/>
    <bean id="intersectionDao" class="com.intersections.dao.IntersectionDao" />
    <bean id="pedestrianDisplayDao" class="com.intersections.dao.PedestrianDisplayDao"/>
    <bean id="pedestrianPushButtonDao" class="com.intersections.dao.PedestrianPushButtonDao"/>
    <bean id="poleDao" class="com.intersections.dao.PoleDao"/>
    <bean id="signalHeadDao" class="com.intersections.dao.SignalHeadDao"/>
    <bean id="trafficSignalControllerDao" class="com.intersections.dao.TrafficSignalControllerDao"/>

    <bean id="userDao" class="com.intersections.dao.UserDao" />
    <bean id="exportExcel" class="com.intersections.service.ExportExcel" />

</beans>

spring-security.xml

<?xml version='1.0' encoding='UTF-8' ?>
<beans:beans    xmlns="http://www.springframework.org/schema/security"
                xmlns:beans="http://www.springframework.org/schema/beans"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                                    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd" >

    <http pattern="/assets/**" security="none" />

    <http auto-config="true">
        <access-denied-handler error-page="/403"/>
        <intercept-url pattern="/login" access="permitAll()"/>
        <intercept-url pattern="/" access="permitAll()"/>
        <intercept-url pattern="/pdf/**" access="hasRole('USER')"/>
        <intercept-url pattern="/use/**" access="hasRole('USER')"/>
        <intercept-url pattern="/insert/**" access="hasRole('FULLUSER')"/>
        <intercept-url pattern="/update/**" access="hasRole('FULLUSER')"/>
        <form-login login-page="/login"
                    default-target-url="/" />
        <logout />

    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="userDao" />
    </authentication-manager>

</beans:beans>

最佳答案

您需要在更新方法中添加以下内容

session.flush();

关于java - Hibernate 不生成更新的 sql 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41273399/

相关文章:

Java BorderLayout 等尺寸/对齐方式

java - 从数据库中检索 java 对象列表而不是请求的对象列表

java - Hibernate 如何使用 setCacheMode(CacheMode.IGNORE) 抛出 NonUniqueObjectException?

java - Spring Boot 多数据源 - 只工作一个

java - Spring 4 Framework Internationalization 无法使用 thymeleaf 识别来自资源属性文件的消息

java - java中ArrayList的区别列表

java - 无法使用 DriverManager 连接到 mysql 数据库

java - 如何为多对多关联编写 HQL 查询?

java - "HttpMessageNotReadableException Required request body is missing"尝试发出发布请求时

javascript - AngularJs 表单发布数据在我的 spring Controller 中给出空值