spring+hibernate+mysql实例 以及怎样用注解方式实现这个例子

1.建数据库表

2.新建java项目,导包(spring,hibernate,mysql所需要的包)

项目结构:

项目所需包:

3.创建实体类

package cn.xxs.entity;

import java.util.Date;

public class User {
	private Integer id;
	private String name;
	private String pwd;
	private Date createDate;
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, String pwd, Date createDate) {
		super();
		this.id = id;
		this.name = name;
		this.pwd = pwd;
		this.createDate = createDate;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + ", createDate=" + createDate + "]";
	}
	
	
}

4.实体类的配置文件

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
		<!-- name为实体类包名加类名 table为数据库表名 -->
		<class name="cn.xxs.entity.User" table="user">
		<!-- 主键 -->
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <!-- 字段 -->
        <property name="name" type="java.lang.String" column="name"/>
        <property name="pwd" type="java.lang.String" column="pwd"/>
        <property name="createDate" type="java.util.Date" column="createDate"/>
    </class>

</hibernate-mapping>

5.接口与接口的实现

        

package cn.xxs.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import cn.xxs.dao.UserDao;
import cn.xxs.entity.User;

public class UserDaoImpl implements UserDao{
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

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

	@Override
	public void print() {		
		Session session =sessionFactory.openSession();
		//查询数据库第三条数据
		User u = session.get(User.class, 3);
		//打印
		System.out.println(u.toString());
		
	}

}
package cn.xxs.service.impl;

import cn.xxs.dao.UserDao;
import cn.xxs.service.UserService;
import cn.xxs.util.BeanUtil;

public class UserServiceImpl implements UserService{

	private UserDao userDao;
	
	//只需设置getter和setter方法,它可自动注入过来
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void print() {
		userDao.print();
	}

}

6.测试类

package cn.xxs.action;

import org.junit.Test;

import cn.xxs.entity.User;
import cn.xxs.service.UserService;
import cn.xxs.util.BeanUtil;

public class UserAction {
	
	private UserService userService;	
	
	//在action层中,同样需设置getter和setter方法,把需要的ben注入过来
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Test
	public void test() {	
		//但是 还是需要读取一次bean.xml配置文件,但其他层已经在bean.xml中配置好了,不需要读取配置文件
		userService = (UserService) BeanUtil.getBean("userService");	
		userService.print();
	}
}

7.工具类

package cn.xxs.util;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanUtil {    
    public static Object getBean(String beanName) {
        return new ClassPathXmlApplicationContext("bean.xml").getBean(beanName);
    }
}


8.配置bean.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.xsd">  
      <!-- id:定义一唯一的名字
    class:指的是把那个类交给spring管理
     -->     
    <bean id="userDao" class="cn.xxs.dao.impl.UserDaoImpl">
    	<property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
     
     <bean id="userService" class="cn.xxs.service.impl.UserServiceImpl">
     	<!--name:指的是userService定义的属性的名字userDao
     		ref:把所需要的bean注入当前类,userDaoImpl上面配置的bean的id
      	 -->
     	<property name="userDao" ref="userDao"></property>
     </bean> 
     
     <bean id="userAction" class="cn.xxs.action.UserAction">
     	<property name="userService" ref="userService"></property>
     <!-- 在bean.xml中可以配置属性注入方式实现,这样使用可以减少去读取配置文件 -->
     </bean> 
     
     <!-- 配置数据源
     		destroy-method:关闭数据库连接时,它自动销毁连接
      -->
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
	<!-- 配置sessionFactory,把myDataSource注入给下面这个类 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 把myDataSource注入到LocalSessionFactoryBean中 -->
        <property name="dataSource" ref="myDataSource"/>
        <property name="mappingResources">
            <list>
                <value>User.hbm.xml</value>
            </list>
        </property>
        <!-- hibernate其他配置 -->
        <property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>

    </bean>
     
     
</beans>  

效果

9.其中配置数据源,连接数据库还有其他方式。

1>在src下添加jdbc配置文件jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hibernate
jdbc.username=root
jdbc.password=root

2>更改bean.xml部分代码

<!-- 配置数据源
             destroy-method:关闭数据库连接时,它自动销毁连接
      -->
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

更改为

<!-- 加载jdbc配置文件 -->
     <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:jdbc.properties" />    
    </bean>
     
     <!-- 配置数据源
             destroy-method:关闭数据库连接时,它自动销毁连接
      -->
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

就ok,重新测试项目,会得到一样的结果。

 

 

10.那么,接下来我们使用“注解”把项目一步步优化。

首先我们添加hibernate注解

1>我们先更改bean.xml

把<property name="mappingResources">
            <list>
                <value>User.hbm.xml</value>
            </list>
        </property>

更改为

 <!-- 注解方法 -->
        <property name="packagesToScan" value="cn.xxs"></property>

2>此时,你可以把User.hbm.xml给delete了

3>在实体类添加注解(注意:我的实体类的属性名与数据库字段名相同,所以一些注解可以省略)

package cn.xxs.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class User {
	private Integer id;
	private String name;
	private String pwd;
	private Date createDate;
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, String pwd, Date createDate) {
		super();
		this.id = id;
		this.name = name;
		this.pwd = pwd;
		this.createDate = createDate;
	}
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + ", createDate=" + createDate + "]";
	}
	
	
}

然后我们添加spring注解

1>进一步更改bean.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:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"      
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        ">    
     
     <!-- 开启注解驱动 -->
     <context:annotation-config />
     <!-- 开启组件扫描 -->
     <context:component-scan base-package="cn.xxs"/>
     
     <!-- 加载jdbc配置文件 -->
     <bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations" value="classpath:jdbc.properties" />	
	</bean>
     
     <!-- 配置数据源
     		destroy-method:关闭数据库连接时,它自动销毁连接
      -->
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
	<!-- 配置sessionFactory,把myDataSource注入给下面这个类 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 把myDataSource注入到LocalSessionFactoryBean中 -->
        <property name="dataSource" ref="myDataSource"/>
        
        <!-- 注解方法 -->
        <property name="packagesToScan" value="cn.xxs"></property>
        
        <!-- hibernate其他配置 -->
        <property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>

    </bean>
     
     
</beans>  

2>进一步更改dao层和service层接口的实现为

3>进一步更改测试类为

4>测试结果仍为相同,说明成功了,哈哈,是不是越来越简单了呢。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值