⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 customizableentitymanagerimpl.java

📁 向数据库添加用户自定义字段
💻 JAVA
字号:
package com.enterra.customfieldsdemo;

import java.util.Iterator;

import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue;

public class CustomizableEntityManagerImpl implements CustomizableEntityManager {
	private Component customProperties;

	private Class entityClass;

	public CustomizableEntityManagerImpl(Class entityClass) {
		this.entityClass = entityClass;
	}

	public Class getEntityClass() {
		return entityClass;
	}

	public Component getCustomProperties() {
		if (customProperties == null) {
			Property property = getPersistentClass().getProperty(CUSTOM_COMPONENT_NAME);
			customProperties = (Component) property.getValue();
		}
		return customProperties;
	}

	public void addCustomField(String name) {
		SimpleValue simpleValue = new SimpleValue();
		simpleValue.addColumn(new Column("fld_" + name));
		simpleValue.setTypeName(String.class.getName());

		PersistentClass persistentClass = getPersistentClass();
		simpleValue.setTable(persistentClass.getTable());

		Property property = new Property();
		property.setName(name);
		property.setValue(simpleValue);
		getCustomProperties().addProperty(property);

		updateMapping();
	}

	public void removeCustomField(String name) {
		Iterator propertyIterator = customProperties.getPropertyIterator();

		while (propertyIterator.hasNext()) {
			Property property = (Property) propertyIterator.next();
			if (property.getName().equals(name)) {
				propertyIterator.remove();
				updateMapping();
				return;
			}
		}
	}

	private synchronized void updateMapping() {
		MappingManager.updateClassMapping(this);
		HibernateUtil.getInstance().reset();
		// updateDBSchema();
	}

	private PersistentClass getPersistentClass() {
		return HibernateUtil.getInstance().getClassMapping(this.entityClass);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -