为什么数据库没有映射?

时间:2015-05-28 03:49:06

标签: java spring hibernate

我使用spring mvc和hibernate开发了服务器程序。 我需要在MySQL表中使用max函数。 所以,我搜索两种方式。 一个是

public void getMaxImageNumber() {
        Session session = this.sessionFactory.getCurrentSession();
        String hql = "select max(festival_image_number) from festival_image";
        List list = session.createQuery(hql).list();
        int maxNumber = ((Integer) list.get(0)).intValue();

        System.out.println(maxNumber);
}

另一个是

public void getMaxImageNumber() {

        DetachedCriteria maxId = DetachedCriteria.forClass(FestivalImage.class)
                .setProjection(Projections.max("festival_image_number"));
        List resultList = session.createCriteria(FestivalImage.class)
                .add(Property.forName("festival_image_number").eq(maxId))
                .list();
        Iterator iter = resultList.iterator();
        for (; iter.hasNext();) {
            System.out.println(iter.next().toString());
        }
    }

当我使用第二种方法时,列表是空的......我不知道为什么。所以,我尝试其他方式。这是第一种方法。但是,当我尝试此方法时,会发生org.hibernate.hql.internal.ast.QuerySyntaxException错误。 我已经映射了表... 请帮帮我..

这是ModelImage的模型类。

package kr.ac.jbnu.jinggumdari.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name="festival_image")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class FestivalImage {
    @Id
    @Column(name="festival_image_number")
    private String festivalImageNumber;

    @Column(name="festival_image_path")
    private String festivalImagePath;

    @Column(name="festival_image_file_name")
    private String festivalImageFileName;

    @JoinColumn(name = "festival_number", table = "festival_info")
    private String festivalNumber; 


    public FestivalImage(String festivalImageNumber, String festivalNumber,
            String festivalImagePath, String festivalImageFileName) {
        this.festivalImageNumber = festivalImageNumber;
        this.festivalNumber = festivalNumber;
        this.festivalImagePath = festivalImagePath;
        this.festivalImageFileName = festivalImageFileName;
    }

    public String getRegionFestivalImageNumber() {
        return festivalImageNumber;
    }
    public void setRegionFestivalImageNumber(String festivalImageNumber) {
        this.festivalImageNumber = festivalImageNumber;
    }   

    public String getFestivalNumber() {
        return festivalNumber;
    }
    public void setFestivalNumber(String festivalNumber) {
        this.festivalNumber = festivalNumber;
    }   

    public String getFestivalImagePath() {
        return festivalImagePath;
    }
    public void setFestivalImagePath(String festivalImagePath) {
        this.festivalImagePath = festivalImagePath;
    }   

    public String getFestivalImageFileName() {
        return festivalImageFileName;
    }
    public void setFestivalImageFileName(String festivalImageFileName) {
        this.festivalImageFileName = festivalImageFileName;
    }   

    @Override
    public String toString(){
        return festivalImageNumber + "," + festivalNumber + "," + festivalImagePath + "," + festivalImageFileName;
    }

}

这是servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- DispatcherServlet Context: defines this servlet's request-processing 
        infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <beans:bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <beans:property name="favorPathExtension" value="true" />
        <beans:property name="ignoreAcceptHeader" value="true" />

        <beans:property name="mediaTypes">
            <beans:map>
                <beans:entry key="json" value="application/json" />
                <beans:entry key="html" value="text/html" />
            </beans:map>
        </beans:property>
    </beans:bean>

    <context:component-scan base-package="kr.ac.jbnu.jinggumdari" />

    <beans:bean
        class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <beans:property name="url"
            value="jdbc:mysql://localhost:3306/jinggumdari" />
        <beans:property name="username" value="root" />
        <beans:property name="password" value="mysql1234" />
    </beans:bean>

    <!-- Hibernate 4 SessionFactory Bean definition -->
    <beans:bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="annotatedClasses">
            <beans:list>
                <beans:value>kr.ac.jbnu.jinggumdari.model.Member</beans:value>
                <beans:value>kr.ac.jbnu.jinggumdari.model.Festival</beans:value>
                <beans:value>kr.ac.jbnu.jinggumdari.model.FestivalImage</beans:value>
            </beans:list>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>

    <beans:bean id="memberDAO" class="kr.ac.jbnu.jinggumdari.DAO.MemberDAOImpl">
        <beans:property name="sessionFactory"
            ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="memberService"
        class="kr.ac.jbnu.jinggumdari.serviceImplementation.MemberManageServiceImpl">
        <beans:property name="memberDAO" ref="memberDAO"></beans:property>
    </beans:bean>

    <beans:bean id="festivalDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalDAOImpl">
        <beans:property name="sessionFactory"
            ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="festivalService"
        class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalManageServiceImpl">
        <beans:property name="festivalDAO" ref="festivalDAO"></beans:property>
    </beans:bean>

    <beans:bean id="festivalImageDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalImageDAOImpl">
        <beans:property name="sessionFactory"
            ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="festivalImageService"
        class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalImageServiceImpl">
        <beans:property name="festivalImageDAO" ref="festivalImageDAO"></beans:property>
    </beans:bean>

    <beans:bean id="reviewDAO" class="kr.ac.jbnu.jinggumdari.DAO.ReviewDAOImpl">
        <beans:property name="sessionFactory"
            ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="reviewService"
        class="kr.ac.jbnu.jinggumdari.serviceImplementation.ReviewManageServiceImpl">
        <beans:property name="reviewDAO" ref="reviewDAO"></beans:property>
    </beans:bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

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

这是具有getMaxImageNumber()的FestivalImageDAOImple。

package kr.ac.jbnu.jinggumdari.DAO;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import kr.ac.jbnu.jinggumdari.model.FestivalImage;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

public class FestivalImageDAOImpl implements FestivalImageDAO {

    private static final Logger logger = LoggerFactory
            .getLogger(FestivalImageDAO.class);
    private SessionFactory sessionFactory;
    private boolean isSuccess;

    public void setSessionFactory(SessionFactory sf) {
        this.sessionFactory = sf;
    }

    @Override
    @Transactional
    public boolean addFestivalImage(FestivalImage festivalImage) {
        isSuccess = false;
        Session session = this.sessionFactory.getCurrentSession();
        session.persist(festivalImage);
        logger.info("FestivalImage saved successfully, FestivalImage Details="
                + festivalImage);
        isSuccess = true;
        return isSuccess;
    }

    @Override
    @Transactional
    public boolean modifyFestivalImage(FestivalImage festivalImage) {
        isSuccess = false;
        Session session = this.sessionFactory.getCurrentSession();
        session.update(festivalImage);
        logger.info("FestivalImage modified successfully, FestivalImage Details="
                + festivalImage);
        isSuccess = true;
        return isSuccess;
    }

    @Override
    @Transactional
    public boolean removeFestivalImage(String festivalImageNumber) {
        isSuccess = false;
        Session session = this.sessionFactory.getCurrentSession();
        FestivalImage festivalImage = (FestivalImage) session.load(
                FestivalImage.class, new String(festivalImageNumber));
        if (null != festivalImage) {
            session.delete(festivalImage);
        }
        logger.info("FestivalImage deleted successfully, festivalImageNumber details="
                + festivalImageNumber);
        isSuccess = true;
        return isSuccess;
    }

    @Override
    @Transactional
    public FestivalImage getFestivalImage(String festivalImageNumber) {
        Session session = this.sessionFactory.getCurrentSession();
        FestivalImage festivalImage = (FestivalImage) session.load(
                FestivalImage.class, new String(festivalImageNumber));
        logger.info("FestivalImage loaded successfully, FestivalImage details="
                + festivalImageNumber);
        return festivalImage;
    }

    @Override
    @Transactional
    public Vector<FestivalImage> getFestivalImages() {
        Session session = this.sessionFactory.getCurrentSession();
        logger.info("FestivalImage loaded successfully");
        return null;
    }

    @Override
    @Transactional
    public void getMaxImageNumber() {
        Session session = this.sessionFactory.getCurrentSession();
        String hql = "select max(festival_image_number) from festival_image";
        List list = session.createQuery(hql).list();
        int maxNumber = ((Integer) list.get(0)).intValue();

        System.out.println(maxNumber);
//      DetachedCriteria maxId = DetachedCriteria.forClass(FestivalImage.class)
//              .setProjection(Projections.max("festival_image_number"));
//      List resultList = session.createCriteria(FestivalImage.class)
//              .add(Property.forName("festival_image_number").eq(maxId))
//              .list();
//      Iterator iter = resultList.iterator();
//      for (; iter.hasNext();) {
//          System.out.println(iter.next().toString());
//      }
    }

    // @Override
    // @Transactional
    // public void getMaxImageNumber() {
    // Session session = this.sessionFactory.getCurrentSession();
    // DetachedCriteria maxId = DetachedCriteria.forClass(FestivalImage.class)
    // .setProjection(Projections.max("festival_image_number"));
    // List resultList =
    // session.createCriteria(FestivalImage.class).add(Property.forName("festival_image_number").eq(maxId))
    // .list();
    // Iterator iter = resultList.iterator();
    // for(;iter.hasNext();){
    // System.out.println(iter.next());
    // }
    // // Criteria c = session.createCriteria(FestivalImage.class);
    // // Order order;
    // // c.addOrder(order.);
    // // c.setMaxResults(1);
    // // return (FestivalImage)c.uniqueResult();
    // }
}

1 个答案:

答案 0 :(得分:0)

您在查询中使用了列名&#34; festival_image_number&#34; 需要使用来自该类的字段名称( festivalImageNumber ),您的两个功能现在都在工作

使用HQL查询...

String hql = "Select max(festivalImageNumber) from FestivalImage";

与标准

DetachedCriteria maxId = DetachedCriteria.forClass(FestivalImage.class)
                    .setProjection(Projections.max("festivalImageNumber"));
List resultList = session.createCriteria(FestivalImage.class)
                    .add(Property.forName("festivalImageNumber").eq(maxId))
                    .list();