views:

55

answers:

2

Sadly, I forgot to take the code from work with me today. But maybe this little example will clarify things.

I use hibernate to map a bean to a table.

Example:

import javax.persistence.column;
….
String columnameA;
….
@Column(name="columnameA")
public String getColumname(){
  return columnameA
}
….

I do not want to hardcode the columnname (“columnameA”) in my sourcecode, because I need to switch the columname without building the entire project. I wanted to use something like:

@Column(name=getColumnName())

This does not work. The idea is, to to write the columnname somewhere in the jndi tree and use it at startup. So i only need to restart the application to change the columnname.

The only way around this problem – which I can think of – is to write my own annotation, which extends the hibernate class. Is there a simpler way of doing this?

A: 

The only values you can assign to attributes are constant values, specified by hand, or stored in public static final variables.

Annotations do not define behavior, but only meta-informations about class, methods and the likes. You can specify behavior in annotation processors, that read your annotations and generate new source code or other files.

Writing an annotation processo is beyond my knowledge, but you could find other information in the Annotations Processing Tool guide by Sun.

frm
+1  A: 

You can't achieve this with annotations, but a solution to your specific problem is to implement a custom NamingStrategy:

public class NamingStrategyWrapper implements NamingStrategy {
    private NamingStrategy target;

    public NamingStrategyWrapper(NamingStrategy target) {
        this.target = target;
    }

    public String columnName(String arg0) {
        if ("columnameA".equals(arg0)) return getColumnName();
        else return target.columnName(arg0);        
    }

    ...
}

-

AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.setNamingStrategy(new NamingStrategyWrapper(cfg.getNamingStrategy()));
factory = cfg.configure().buildSessionFactory();
axtavt