原来最流行的web开发三大框架 ssh。现在新出现了ssm。m为hibernate的替代者——mybatis。
如果是第一次使用数据持久化框架,推荐先使用hibernate,熟悉一些基本的原理,再使用mybatis更顺手些。
mybatis为hibernate的简化版,如果要使用高级些的功能还推荐使用hibernate。
我使用的是maven项目管理工具。所以引用框架很简单,加一个dependency即可。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
在src/main/resource文件夹中加入hibernate.cfg.xml的配置文件。并设置数据库的名称、用户名、密码以及驱动程序
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 各属性的配置 -->
<property name="show_sql">true</property>
<!-- 一次读的数据库记录数 -->
<property name="jdbc.fetch_size">50</property>
<!-- 设定对数据库进行批量删除 -->
<property name="jdbc.batch_size">30</property>
<!--驱动程序 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- JDBC URL -->
<property name="connection.url">jdbc:mysql://localhost/multisensorpositioningsystem?characterEncoding=utf-8</property>
<!-- 数据库用户名 -->
<property name="connection.username">root</property>
<!-- 数据库密码 -->
<property name="connection.password"></property>
<mapping class="hibernate.User"/>
</session-factory>
</hibernate-configuration>
编写一个持久化对象,只是pojo加上了一些hibernate的注解
package hibernate;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
@javax.persistence.Entity
@Table(name = "newsusr")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String userName;
public User() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
此时注意@Entity这个注解是@javax.persistence.Entity。而不是hibernate包下的Entity,如果使用了后者会提示找不到类。
@Entity 注解声明这是一个持久化类
@Table 指定该类的映射表
@Id 指定标识属性,标识为主键
@GeneratedValue 用于指定主键生成策略IDENTITY为自动增长
编写类后记得在hibernate.cfg.xml中加入映射对象的配置
<mapping class="hibernate.User"/>
</session-factory>
因为hibernate不但支持web应用还支持普通的java application。所以为我们测试提供了方便。
public static void main(String[] args) {
Configuration conf = new Configuration().configure();
org.hibernate.service.ServiceRegistry service = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(service);
Session sess = sf.openSession();
org.hibernate.Transaction tx = sess.beginTransaction();
User u = new User();
u.setUserName("1312312312312");
sess.save(u);
tx.commit();
sess.close();
sf.close();
}
成功执行后,程序会在控制台输出sql语句,因为我们在hibernate.cfg.xml里设置了show_sql为true。设置为false可以关闭开关。
Hibernate: insert into newsusr (userName) values (?)
本文介绍SSM框架中MyBatis作为Hibernate替代者的角色,并通过实例展示了如何使用Hibernate进行简单的数据持久化操作,包括配置、实体类定义及基本的增删改查功能。
2204

被折叠的 条评论
为什么被折叠?



