工具用的是Inteli ideaJ 2017.2
先放个完整目录
还有所有用到的jar包,idea自动下载的包就不放了,都在lib里
数据库表
新建项目的时候,记得把Spring,SpringMVC和Hibernate都勾上,进去后自带了这些xml文件
在src目录下建立包
StudentInterface代码如下
package com.limbo.service;
import com.limbo.entity.Student;
public interface StudentInterface {
public void add(Student student);
}
package com.limbo.service;
import com.limbo.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class StudentImpl implements StudentInterface{
@Qualifier("sessionFactory")
@Autowired
private SessionFactory sessionFactory;
@Override
public void add(Student student) {
Session s = sessionFactory.openSession();
Transaction tx= s.beginTransaction();
s.save(student);
tx.commit();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
之后写xml文件
applicationContext代码(数据库用户名密码请自行修改,其中数据库url后面不跟时区属性的话我这里会报错,请注意)
<?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">
<!-- data connection -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"> <