Hibernate NamingStrategy方式 向月表中写日志

按月命名的日志表如 log_YYMM : log_1011,log_1012,表结构完全相同,只是表名不同,通过命名策略实现存数据时自动创建和写入到相应的月表中。

自动创建表,在Hibernate的配置文件中设hbm2ddl.auto 为 update
<hibernate-configuration>

<session-factory>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="connection.url">jdbc:mysql:///test</property>
	<property name="connection.username">root</property>
	<property name="connection.password">root</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="myeclipse.connection.profile">mysql</property>

	<property name="hbm2ddl.auto">[b]update[/b]</property>

	<mapping class="db.TDiykey" />
	<mapping class="db.Person" />

</session-factory>

</hibernate-configuration>


/**
 * 月表命名策略
 * 
 * @author hzhlu
 * 
 */
public class MyNamingStrategy extends DefaultNamingStrategy {

	private static final long serialVersionUID = 1L;

	public static final MyNamingStrategy INSTANCE = new MyNamingStrategy();
	private static final DecimalFormat df = new DecimalFormat();
	private static ArrayList<String> rollingTables = new ArrayList<String>();
	static {
		rollingTables.add("PERSON");
		df.applyPattern("00");
	}

	/**
	 * 向月表中保存数据
	 * 
	 * @see net.sf.hibernate.cfg.NamingStrategy#tableName(java.lang.String)
	 */
	public String tableName(String tableName) {
		String stroeTable = tableName;
		// 对指定的表名计算月表的实际存储表名
		if (rollingTables.contains(tableName.toUpperCase())) {
			stroeTable += "_" + df.format(Calendar.getInstance().get(Calendar.YEAR) % 100)
					+ df.format(Calendar.getInstance().get(Calendar.MONTH) + 1);
			System.out.println("store record into [" + stroeTable + "]");
		}

		return stroeTable;
	}

}


修订自动生成的HibernateSessionFactory 增加命名策略,只需添加一行即可。

configuration.setNamingStrategy(MyNamingStrategy.INSTANCE);


public class MySessionFactory {
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static Configuration configuration = new AnnotationConfiguration();
	private static org.hibernate.SessionFactory sessionFactory;
	private static String configFile = CONFIG_FILE_LOCATION;

	static {
		try {
			// 添加月表命名策略
			configuration.setNamingStrategy(MyNamingStrategy.INSTANCE);
			
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}




测试程序
public class MyNamingStrategyTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		test2();
	}

	public static void test2() {
 		Session session = MySessionFactory.getSession();
		Transaction tx = session.beginTransaction();

		Person person = new Person();
		person.setId(new Random().nextInt());
		person.setFirstName("firstName");
		person.setLastName("lastName");
		session.save(person);

		TDiykey tDiykey = new TDiykey();
		tDiykey.setDbid("" + System.currentTimeMillis() % 999999);
		tDiykey.setNotes("notes");
		session.save(tDiykey);

		tx.commit();
		session.close();

		System.out.println("ok!");
 	}

}

你可能感兴趣的:(数据结构,Hibernate,xml,mysql,jdbc)