java - 使用 Spring DAO 和 Hibernate 的数据访问层。问题

标签 java hibernate spring jakarta-ee

大家好,这是我在 spring 和 hibernate 中的第一个应用程序。所以请耐心等待我提出一些愚蠢的问题:)。 我在 netbeans 6.7 中创建了一个简单的 java 应用程序。 这是我的 daos 接口(interface) 用户DAO

package Dao;

import Entities.Users;

public interface UsersDAO {
    public Long GetIdByUsernameAndPasswor(String username, String password);
    public Users GetAllByID(Long id);
    public boolean Create(Users user);
    public boolean Delete(Users user);
    public boolean Edit(Users user);
}

和 ContactDAO

package Dao;

import Entities.Contacts;
import java.util.List;

public interface ContactsDAO {
    public List GetAll();
    public Contacts GetAllById(Long Id);
    public boolean Create(Contacts contact);
    public boolean Delete(Contacts contact);
    public boolean Edit(Contacts contact);
}

及其实现

package Dao.DaoImpl;

import Dao.UsersDAO;
import Entities.Users;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class UserDAOImpl  extends HibernateDaoSupport implements UsersDAO {
    //    private SessionFactory sessionFactory;
    public UserDAOImpl(){}

    public Long GetIdByUsernameAndPasswor(String username, String password)
    {
        try
        {
             return DataAccessUtils.longResult(getHibernateTemplate().find("select u.user_id from Users u where u.username=? and u.password", new Object[] {username, password}) );
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return Long.parseLong("0");
        }
    }

    public Users GetAllByID(Long id) {
       try
       {
           return (Users) getHibernateTemplate().get(Users.class, id);
       }
       catch(Exception ex)
       {
            ex.printStackTrace();
            return new Users();
       }
    }

    public boolean Create(Users user) {
       try
       {
            getHibernateTemplate().save(user);
            return true;
       }
       catch(Exception ex)
       {
           ex.printStackTrace();
           return false;
       }
    }

    public boolean Delete(Users user) {
       try
       {
           getHibernateTemplate().delete(user);
           return true;
       }
       catch(Exception ex)
       {
           ex.printStackTrace();
           return false;
       }
    }

    public boolean Edit(Users user) {
       try
       {
           getHibernateTemplate().saveOrUpdate(user);
           return true;
       }
       catch(Exception ex)
       {
           ex.printStackTrace();
           return false;
       }
      }
    }
<小时/>
package Dao.DaoImpl;

import Dao.ContactsDAO;
import Entities.Contacts;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ContactsDAOImpl extends HibernateDaoSupport implements ContactsDAO{
    public ContactsDAOImpl(){}

    public List GetAll() {
        try
        {
            return getHibernateTemplate().find("from Contacts");
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    public Contacts GetAllById(Long Id) {
      return (Contacts) getHibernateTemplate().get(Contacts.class, Id);
    }

    public boolean Create(Contacts contact) {
        try
        {
            getHibernateTemplate().save(contact);
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

    public boolean Delete(Contacts contact) {

        try
        {
            getHibernateTemplate().delete(contact);
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

    public boolean Edit(Contacts contact) {

        try
        {
            getHibernateTemplate().saveOrUpdate(contact);
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
         }
        }
    }

我的spring配置文件位于Resources.so文件夹下,所以通常路径是Resouces/contactmanagement.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />

    <property name="url" value="jdbc:mysql://localhost:3306/ContactsMan" />
    <property name="username" value="root" />
    <property name="password" value="letmein" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.SessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResouces">
        <list>
            <value>Resources/users.hbm.xml</value>
            <value>Resources/contacts.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>
<bean id="usersdao" class="Dao.DaoImpl.UserDAOImpl">
    <property name="sessionFactory" ref="sessionFactory">
</bean>
<bean id="contactsdao" class="Dao.DaoImpl.ContactDAOImpl">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

映射文件位于同一资源文件夹 users.hbm.xml contact.hbm.xml 下

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="Entities.Contacts" table="contacts">
            <id name="contact_id">
                    <generator class="increment"/>
            </id>
            <many-to-one cascade="" class="Users" name="user"/>
            <property name="firstname" />
            <property name="lasstname" />
            <property name="cellphone1" />
            <property name="cellphone2" />
            <property name="telephone" />
            <property name="email" />
        </class>
    </hibernate-mapping>
<小时/>
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="Entities.Users" table="users">
            <id name="users_id">
                <generator class="increment"/>
            </id>
            <bag name="contacts" inverse="true" lazy="true">
                <key column="user_id"/>
                <one-to-many class="Contacts"/>
            </bag>

            <property name="username"/>
            <property name="passsword"/>
            <property name="city"/>
            <property name="country"/>

        </class>
    </hibernate-mapping>

这终于是我的主课

package main;
import Dao.UsersDAO;
import Entities.Users;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext
public class contactmanagement {

public static void main(String[] args)
{
    ApplicationContext ctx = new ClassPathXmlApplicationContext("Resources/contactmanagement.xml");
    UsersDAO usersdao = (UsersDAO) ctx.getBean("usersdao");
    Users user = new Users();
    user.setUsername("me");
    user.setPassword("mypass");
    user.setCity("somecity");
    user.setCountry("somecountry");

    usersdao.Create(user);
    System.out.println("created");
 }

当我运行这个时,它说给出一个摘要“没有定义名为'usersdao'的bean” 请问我做错了什么? 这里还有一个关于 DAO 实现类的问题。我应该设置属性 setSessionFactory 吗?或者 spring 通过 getHibernateTemplate() 处理所有事情? 请让我完成这个。感谢您的阅读。我知道它很长;)

最佳答案

我可以建议看看使用 Spring 注解吗?我并不是想让您先去解决另一件事,但是一旦您掌握了它的窍门,它就比让所有配置和映射文件一起工作要容易得多。

第 3.11 和 3.12 章中有一些与此相关的非常详细的信息: Spring Documentation Chapter 3. The IoC container 但基本上可以归结为:

  • 您可以使用 @Repository(或 @Service)注释要定义为 Bean 的 DAO 类。
  • 无论何时需要使用此类 DAO,您都可以使用以下方式在类中声明一个字段: @Autowired MyExampleDAO myDao; (这些类本身也应该用 @Service 注释才能工作(或者还有其他方法吗?))
  • 配置 Spring 来查找这些注释,它会执行此操作,以便在您需要时总能找到适合您的 Bean 的实现。

作为示例,我的整个 spring 配置如下所示:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <context:component-scan base-package="org.path.to.your.base.package" />

    <!-- Transaction Manager -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven />

    <!-- Session Factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="configLocation" value="hibernate.cfg.xml" />
    </bean>
</beans>

示例 DAO 如下所示:

@Repository
public class UserHibDAO extends GenericHibernateDAO<HopeUser> implements UserDAO {
    public IUser findByName(String name) {
        return (User) createCriteria(Restrictions.naturalId().set("name", name)).uniqueResult();
    }
}

使用这个 DAO 看起来像这样:

@Service
public class Installer {
    private static final Logger log = Logger.getLogger(Installer.class);

    public static void main(String[] args) throws Exception {
        Installer inst = (Installer) SpringUtil.getContext().getBean("installer");
        inst. storeUsers();
        log.info("Done");
    }

@Autowired
private UserDAO userdao;

@Transactional
public void storeUsers() {
    userdao.makePersistent(new User("Tim"));

    log.info("Users stored");
}
}

要特别注意最后一个代码示例中的 main 方法:这是您必须使用的方法,而不是 new Installer() 来使 Autowiring 工作。

无论如何,希望这个例子对您有所帮助,我意识到它不是对您问题的直接答案,而是当前问题的替代解决方案。

关于java - 使用 Spring DAO 和 Hibernate 的数据访问层。问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1110165/

相关文章:

java - 如何从 Internet 获取值到 String[] 数组并将其传递到 Android 中的 GridView ?

java - JPQL 连接两个表

java - 如何在保持缓存自动配置的同时添加自定义@Cacheable缓存?

java - Android 应用程序不会记住 USB 权限

java - java中字符串的使用

java - Apache Sling 脚本解析规则如何工作?

java - 如何更改 hibernate 约束名称生成?

java - 如何在运行时检查是否声明了 NamedNativeQuery

java - 使用 CascadeType.ALL 的 JPA 外键约束

java - SpringMVC(Intellij)的 404 错误