Newbie in Hibernate.
I've an existing schema in SQL Server and I used reverse-eng wizard in netbeans to generate POJOs from the schema. Now a decision has been made to switch to MySQL. Is there a way where I can run any hibernate utility to create tables and schema in MySQL from these POJOs?
Thank you
Bo
You can use the SchemaExport tool . It can be used via the command line , ant task or directly use the SchemaExport Class in the java code.
Here is the example to use the SchemaExport class ,
Configuration cfg = new Configuration().configure("your/hibernate/cfg/xml");
SchemaExport schemaExport= new SchemaExport(cfg);
/**First boolean means if print the generated DDL script to the console
Second boolean mean if execute the generated DDL script in the DB*/
schemaExport.create(true, true);
In the hibernate configuration xml , you have to specify your db connection info and your generated POJO from netbeans.
Related
I have to do a project using JPA + Hibernate in which I'm using 3 dialects: MySQL5InnoDBDialect, MSSQL2012Dialect and Oracle12cDialect.
Right now I have a specification which is telling me that for some column from:
Oracle database, I have to use NVARCHAR2(LENGTH) data type
MySql database, I have to use VARCHAR(LENGTH) data type
MSSQL database, I have to use NVARCHAR(LENGTH) data type
... and here is my problem..
If I use:
#Column(name="columnName" length = 255)
private String columnName;
hibernate generates varchar(255) and this is good just for MySQL
If I use:
#Column(name="columnName", columnDefinition="nvarchar2(255)")
private String columnName;
it's not possible in MySQL, i get error because of columnDefinition, but in oracle is okay
I tried to customize MySQL dialect creating
public class CustomMySQL5InnoDBDialect extends MySQL5InnoDBDialect{
public CustomMySQL5InnoDBDialect() {
super();
registerColumnType(Types.NVARCHAR, "nvarchar2($l)");//$l not $1
registerHibernateType(Types.NVARCHAR, StandardBasicTypes.STRING.getName());
}
}
and giving this class in hibernate configuration for MySQL dialect.
I have the same problem in MySQL if I'm using columnDefinition property.
Can you help with this problem please?
The solution is to make use of the feature that the JPA API spec provides you with for just this situation. Define a file orm.xml for each datastore that you need to support, and enable the requisite one when using each database. See this link for details of the file format. That way you don't need to think about hacking the internal features of whichever JPA provider you are using, and you also retain JPA provider portability, as well as database portability
The idea of putting schema specific information info (static) Java annotations is an odd one, even more so when wanting database portability.
I'm using Flyway test extensions with H2 database and MySQL dialect.
Unfortunately, #FlywayTest annotation executes database clean with H2 dialect and ends with error:
org.flywaydb.core.internal.dbsupport.FlywaySqlException:
Unable to drop "PUBLIC"."site"
------------------------------
SQL State : 42S02
Error Code : 42102
Message : Table "site" not found; SQL statement:
DROP TABLE "PUBLIC"."site" CASCADE [42102-193]
at org.flywaydb.core.internal.dbsupport.SchemaObject.drop(SchemaObject.java:82)
at org.flywaydb.core.internal.dbsupport.h2.H2Schema.doClean(H2Schema.java:69)
at org.flywaydb.core.internal.dbsupport.Schema.clean(Schema.java:148)
at org.flywaydb.core.internal.command.DbClean$4.call(DbClean.java:184)
at org.flywaydb.core.internal.command.DbClean$4.call(DbClean.java:181)
at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.exec
However, when I manually run DROP TABLE PUBLIC.site CASCADE (no quotes) from console it ends successfully.
How to force dialect in Flyway test extensions?
This is no problem of the annotation #FlywayTest.
The annotation #FlywayTest call flyway.clean() method.
And Flyway supports for H2 only quoted names for schema and tables.
See class source code on Github https://github.com/flyway/flyway/blob/master/flyway-core/src/main/java/org/flywaydb/core/internal/dbsupport/h2/
I think there will be no plan to support H2 feature modes, such like Mysql, Oracle, ....
You can open a issue here https://github.com/flyway/flyway/issues
I have to generate JPA objects for mysql tables using odata4J , as i am new to web services i have followed some online resources created following tasks;
Created new database connection under "Database Development"
Added eclipse link and mysql connector libraries through windows-> preferences->user library
Changed project Facets to JPA and configured further JPA configurations
Persistence.xml is generated and Populated Transaction Type from "Resource Local" under connection tab in the Persistence.xml
Generated JPA Entities from table by Right clicking on Project and selecting JPA Tools -> Generate entities from Table option.
One Java file is generated with the name of Table name.
I have written one Java class called TestProducer
public class TestProducer implements ODataProducerFactory {
String persistence = "testJPA";
String namespace = "testui5";
int maxResults = 50;
#Override
public ODataProducer create(Properties properties) {
String endpointUri = "http://localhost:8080/TestProducer.svc/";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistence);
JPAProducer producer = new JPAProducer(emf, namespace, maxResults);
DefaultODataProducerProvider.setInstance(producer);
return producer;
}
}
Am able to get result on console by calling create method in TestProducer from Main
But can any one tell me step by step procedure to access JPA Object through http , am not getting any online resouces.Please help me ..thanks in advance.
I have two databases with the same schema inside a Sql 2008 R2 Server, of which names are Database1 and Database2. I connected and performed queries on the Database1, and then changed to Database2 to fetch my entities using the following code
this.ConnectionString = "Server=TestServer; Database=Database2;Trusted_Connection=true";
using (IDataAccessAdapter adapter = new DataAccessAdapter(this.ConnectionString))
{
var entities = new EntityCollection<T>();
adapter.FetchEntityCollection(entities, null);
return entities;
}
(The connection string was set before executing the code).
I debugged the application and looked at the value of the connection string, it pointed to the Database2.
However, when I executed the above code, the result was return from the Database1. And if I looked at SQL Profiler, the statement was executed against Database1.
So, could anyone know what was going on? Why the query was executed against the Database1, not Database2.
PS: If I used the above connection string with plain ADO.NET, I was able to retrieve data from Database2.
Thanks in advance.
I have figured out what was going on. The reason was: by default LLBL Gen Pro uses fully qualified names like [database1].[dbo].[Customer] to access database objects, and the catalog is specified when generating entities. So you can't access objects just by changing the connection string.
Hence, to change to another database you have to override the default catalogue by using following code
var adapter= new DataAccessAdapter(ConnectionString, false,
CatalogNameUsage.ForceName, DbName)
{CommandTimeOut = TenMinutesTimeOut};
More information can be found at the following link
I've inherited a Pylons app that uses SQLAlchemy. I know nothing about SQLAlchemy and very little about Pylons :)
I need to run some raw SQL from within the app. The SQLAlchemy currently seems to be working in the following way (example code):
import myapp.model as model
model.Session.query(model.KeyValue) # existing code
.join(model.Key)
.filter(model.Key.name == name)
).count() == 0, name
How do I get it to run raw SQL? I see that I need an execute() statement, but how exactly do I run it? The following both fail:
model.Session.execute('create table hello_world;')
model.Connection.execute("""
create table hello_world;
""")
What's the magic invocation? There's no reference to a Connection object in the existing code, and I'm not sure how to create one.
You can obtain connection that is used by Session by using its connection method:
connection = model.Session.connection()
Then you can issue your query:
connection.execute('create table hello_world;')
Note that in Pylons model.Session is not a sqlalchemy.orm.session.Session class. It's an instance of sqlalchemy.orm.scoping.ScopedSession. That's how it's created in model.meta module:
Session = scoped_session(sessionmaker())
My first impulse is to recommend trying the execute() method of an instance of Connection, instead of the execute() method of the class itself as your example code suggests that you're doing.
Are you working off of the Pylons Book examples ?