Hibernate
全自动的ORM框架,将操作数据库表转换成操作Java对象,提供Hql语言,并且引入了数据库缓存;
Hibernate使用
- 引入相关包,创建核心配置文件hibernate.cfg.xml
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/java_base?useUnicode=true&characterEncoding=UTF-
8</property>
<property name="connection.username">root</property>
<property name="connection.password">dengh</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 定义hibernate使用mysql数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 配置自动创建|更新|验证数据库表结构,无此需求定义为none-->
<!-- hibernate.hbm2ddl.auto或者hbm2ddl.auto的取值有:create,update,create-drop,validate,其中create表示to build a new database on each run,update表示to modify an existing database,create-drop表示means the same as 'create' but also drops tables when Hibernate closes,validate表示makes no changes to the database。
<property name="hbm2ddl.auto">none</property>//
<!-- 配置在控制台展示相应的sql -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 指定映射的实体类 -->
<mapping class = "com.eshore.hibernate.pojo.Student"/>
</session-factory>
- 创建表配置文件xxx.hbm.xml,或者使用注解来指定Java实体类和数据库表的对应关系(推荐)
@Entity
@Table(name="student")
public class Student {
// 注意到string主键采用的是uuid的生成策略,是产生32位字符,所以数据库字段也需要满足
@Id
@GenericGenerator(name="uuidGen" ,strategy="uuid")
@GeneratedValue(generator="uuidGen")
@Column(name="id")
private String id;
@Column(name="login_name")
private String name;
// @Transient:表明ORM框架将不会去寻找这个属性的映射
@Transient:
private remark;
...
}
- 启动项目,将自动创建数据库表结构,应用中使用session接口来操作数据库,API有save(),createQuery()等方法
public static void main(String[] args){
Configuration cfg = new Configuration().configure();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(sr);
Session session = sf.openSession();
// 实体类添加
Student stu = new Student();
stu.setName("张三5");
// 对应sql中的 start transcation
session.getTransaction().begin();
session.save(stu);
session.getTransaction().commit();
// hql查询
Query query = session.createQuery("from Student");
List<Student> list = query.list();
for(Student stud:list){
System.out.println(stud.getId()+" "+stud.getName());
}
}
- 参考:http://www.yiibai.com/hibernate/generator-classes.html#article-start
Hibernate与Spring的集成
- 将配置文件hibernate.cfg.xml融入到applicationContext.xml中,将sessionFactory交由spring上下文管理,并且实体类使用注解扫描的方式,之后便可以在应用中注入SessionFactory这个bean,进而获取session来操作数据库;
<!-- 指定使用HibernateTransactionManager这个事务管理器,基于注解使用-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.eshore.*"/>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<context:property-placeholder location="classpath:/conf/jdbc.properties" />
{
@Autowired
private SessionFactory sessionFactory
{
Session session = sessionFactory.openSession();
}
}
SpringJPA
- 统一Java持久化Api,仅封装接口,底层然后使用hibernate,openJpa等orm框架;
- 使用
<bean id = "entityManagerFactory" class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 指定Jpa持久化实现厂商类,这里以Hibernate为例 -->
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="packagesToScan" value="com.dengh.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id = "jpaVendorAdapter" class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
main(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-jpa.xml");
JpaDao dao = ctx.getBean(JpaDao.class);
EntityManager entityManager = ctx.getBean(EntityManagerFactory.class).createEntityManager();
EntityTransaction t = entityManager.getTransaction();
t.begin();
StudentOrm s = new StudentOrm();s.setName("liud");s.setAge(25);s.setLevel(1);
entityManager.persist(s);
t.commit();
entityManager.close();
}
小Tips
- 如果遇到实体类无法自动创建表结构:首先查看设置hibernate.hbm2ddl.auto,注意不能省略hibernate,其次查看实体类的注解是否正确,最优是注解放在get方法上,而不是字段上,最后,添加和查看日志。
- GeneratorType.AUTO是JPA的自动生成主键的策略,在mysql中就是自增长,如果你将其添加到一个string的主键上,就会导致建表失败;
来源:CSDN
作者:qq_28128035
链接:https://blog.csdn.net/qq_28128035/article/details/103842307