Ver Mensaje Individual
  #2 (permalink)  
Antiguo 10/12/2009, 11:14
mreparaz
 
Fecha de Ingreso: agosto-2007
Mensajes: 14
Antigüedad: 17 años, 7 meses
Puntos: 0
Respuesta: Agragar mappings automaticamente en Hibernate

Una aclaración, esto lo pude hacer de la siguiente manera, pero quiero saber si hibernate me provee alguna manera más sencilla de hacerlo.

Código:
       public static void init() {
		if (sessionFactory == null)
			try {
				List<Class<?>> clasesPersistentes = obtenerClasesPersistentes();

				AnnotationConfiguration cfg = new AnnotationConfiguration().configure();
				for (Class<?> clasePersistente : clasesPersistentes) {
					cfg.addAnnotatedClass(clasePersistente);
				}
				SchemaExport se = new SchemaExport(cfg);
				se.create(true, true);
				sessionFactory = cfg.buildSessionFactory();
			} catch (Exception e) {
				throw new ExceptionInInitializerError();
			}
	}

private static List<Class<?>> obtenerClasesPersistentes() throws IOException,
			ClassNotFoundException {
		Enumeration<URL> modelos = Thread.currentThread().getContextClassLoader().getResources(
				DIR_MODELO);
		List<File> dirs = new ArrayList<File>();
		while (modelos.hasMoreElements()) {
			URL resource = modelos.nextElement();
			dirs.add(new File(resource.getFile()));
		}
		String packModelo = DIR_MODELO.replace("/", ".");
		ArrayList<Class<?>> clases = new ArrayList<Class<?>>();
		for (File directorio : dirs) {
			clases.addAll(obtenerClases(directorio, packModelo));
		}
		LinkedList<Class<?>> clasesPersistentes = new LinkedList<Class<?>>();
		for (Class<?> clase : clases)
			for (Annotation ann : clase.getAnnotations())
				if (ann instanceof Entity)
					clasesPersistentes.add(clase);
		return clasesPersistentes;
	}

private static List<Class<?>> obtenerClases(File directorio, String packageName)
			throws ClassNotFoundException {
		List<Class<?>> clases = new ArrayList<Class<?>>();
		if (!directorio.exists())
			return clases;

		File[] archivos = directorio.listFiles();
		for (File archivo : archivos) {
			// Agrego todas las clases recursivamente.
			if (archivo.isDirectory()) {
				clases.addAll(obtenerClases(archivo, packageName + "." + archivo.getName()));
			} else if (archivo.getName().endsWith(".class")) {
				clases.add(Class.forName(packageName + '.'
						+ archivo.getName().substring(0, archivo.getName().length() - 6)));
			}
		}
		return clases;
	}
Saludos y gracias.