单列模式&事务规范写法的笔记
本文最后更新于 3372 天前,其中的信息可能已经有所发展或是发生改变。

事务代码规范写法

public class TestHibernate {
	
	@Test
	public void test2(){
		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try {
			sessionFactory = HibernateUtils.getSessionFactory();
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			
			User u = new User();
			u.setUsername("小胡");
			u.setPassword("333");
			session.save(u);
			
			transaction.commit();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			transaction.rollback();
		}finally{
			session.close();
			sessionFactory.close();
		}
	}
	
}

笔记罢了…

package com.glj.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
	static Configuration cfg = null;
	static SessionFactory sessionFactory = null;
	
	static{
		cfg = new Configuration();
		cfg.configure();
		sessionFactory = cfg.buildSessionFactory();
	}
	
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	
}

单例模式

定义:

  1. 在任何地方,任何时候都只能获取某种类型(class)的同一个实例。
  2. 即无论怎么取得的实例均为同一个实例。

需满足三个条件:

  1. 一个私有的静态变量指向自身
  2. 一个私有空参的构造方法
  3. 一个公有的静态方法返回自身

单例模式种类

  1. 饿汉式
  2. 懒汉式

饿汉式代码demo:

  1. 类加载时,马上实例化对象
  2. 在需要时返回此实例化好的对象
class Singleton {
private static Singleton instance = new Singleton();

private Singleton() {
}

public static Singleton getInstance() {
return instance;
}
}

懒汉式代码demo:

  1. 类加载是并不马上实例化对象
  2. 请求这个对象时才开始实例化
  3. 需要同步加锁
class Singleton {
private static Singleton instance ;

private Singleton() {
}

public static Singleton getInstance() {
if (instance == null) {
synchronized("key"){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;

}

Image

评论

  1. Image
    Windows Chrome 49.0.2623.110
    9 年前
    2017-6-02 11:26:59

    学习存下了

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Image
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇