hibernate.properties数据库连接配置
dataSource.password=123
dataSource.username=root
dataSource.databaseName=test
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.dialect=org.hibernate.dialect.MySQL5Dialect
dataSource.serverName=localhost:3306
dataSource.url=jdbc:mysql://localhost:3306/test
dataSource.properties=user=${dataSource.username};databaseName=${dataSource.databaseName};serverName=${dataSource.serverName};password=${dataSource.password}
dataSource.hbm2ddl.auto=update
配置已经完成,下面开始例子
先在数据库建表,例子用的是mysql数据库
CREATE TABLE `test`.`student` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`psw` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
)
建好表后,生成实体类
packagecom.mvc.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student implements Serializable {
private static final long serialVersionUID=1L;
@Id
@Basic(optional=false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id", nullable=false)
private Integer id;
@Column(name="name")
private String user;
@Column(name="psw")
private String psw;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id=id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user=user;
}
public String getPsw() {
return psw;
}
public void setPsw(String psw) {
this.psw= psw;
}
}
Dao层实现
package com.mvc.dao;
import java.util.List;
public interface EntityDao {