In my spring project, I have a service class to create my database and tables. After create the database (which is being done successfully), this method is called:
public void create_tables(String maquina, String usuario, String senha) {
System.out.println("create_tables");
create_properties(maquina, usuario, senha);
Configuration config = new Configuration();
Properties props = new Properties();
FileInputStream fos;
try {
fos = new FileInputStream( "database.properties" );
props.load(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
config.setProperties(props);
try {
String url = props.getProperty("jdbc.url");
Connection conn = DriverManager.getConnection(url,usuario,senha);
SchemaExport schema = new SchemaExport(config, conn);
schema.create(true, true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
insert_default_values();
}
But, despite in the Eclipse console display that the schema was exported successfully, no table is created in my database.
Anyone can see what's wrong here?
UPDATE
database.properties
#propriedades
#Sat May 10 12:52:57 BRT 2014
jdbc.url=jdbc\:postgresql\://localhost\:5432/horario
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=false
jdbc.user=<<my database user>>
jdbc.Classname=org.postgresql.Driver
hibernate.hbm2ddl.auto=update
jdbc.pass=<<my password>>
HibernateConfig.java -> https://github.com/klebermo/webapp_horario_livre/blob/master/src/com/horariolivre/resources/HibernateConfig.java
Entity classes -> https://github.com/klebermo/webapp_horario_livre/tree/master/src/com/horariolivre/entity
Dao classes -> https://github.com/klebermo/webapp_horario_livre/tree/master/src/com/horariolivre/dao
Try adding following code snippet:
config.addAnnotatedClass(com.horariolivre.entity.Atributo.class);
config.addAnnotatedClass(com.horariolivre.entity.Autorizacao.class);
...
Is this what you are looking for?
Related
I'm facing this error:
`Unable to load properties file for MultiWordNet
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:417)
at java.lang.Integer.<init>(Integer.java:660)
at org.itc.mwn.MysqlDictionary.<init>(MysqlDictionary.java:85)`
This is the property file that MysqlDictionary.java is trying to read:
#------------------------------------------------------------
#Properties file properties MultiWordNet API
#Hostname of the MySQL server
MWN_HOSTNAME=localhost
#User
MWN_USER=root
#Password
MWN_PASSWD=
#Database name
MWN_DB=wordnet
#Cache of entity
CACHE_CAPACITY=1000
And,finally, this is the part where the code fails:
public MysqlDictionary() {
try {
connectionParameters = new Properties();
connectionParameters.load(new FileInputStream(new File("./conf/multiwordnet.properties")));
} catch (java.io.IOException ioee) {
System.err.println("Unable to load properties file for MultiWordNet");
}
/// connection drivers instance
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Class.forName("org.gjt.mm.mysql.Driver").newInstance();
} catch(ClassNotFoundException E){
System.err.println("Unable to load driver");
} catch(IllegalAccessException E){
System.err.println("Unable to load driver");
} catch(InstantiationException E){
System.err.println("Unable to load driver");
}
// MultiWordnet db connection
String host = connectionParameters.getProperty("MWN_HOSTNAME");
String user = connectionParameters.getProperty("MWN_USER");
String passwd = connectionParameters.getProperty("MWN_PASSWD");
String dbname = connectionParameters.getProperty("MWN_DB");
Integer cache = new Integer(connectionParameters.getProperty("CACHE_CAPACITY"));
//here is where the parsing fails, but the file is properly written!
try {
DEFAULT_CACHE_CAPACITY = cache.intValue();
String conn = "jdbc:mysql://" + host + "/" + dbname;
this.db = DriverManager.getConnection(conn,user,passwd);
this.stmt = db.createStatement();
System.err.println("Welcome to the MultiWordNet API\nConnection database ...OK\n");
} catch (SQLException E) {
System.out.println("Unable to establish multiwordnet Mysql DB connection on " + host + "(" + user + " - " + passwd + ")");
E.printStackTrace(System.out);
}
The strange thing is that the program started suddenly failing, after it was running correctly
When dealing with File in java don't struggle with relative paths. They are quite unpredictable since they depend on the current working directory on which you don't have total control. Use classpath instead, loading the resource using the class loader:
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("multiwordnet.properties"));
Your problem isn't not being able to parse an integer, but not being able to load your file.
Check out for irregular invisible chars, like <SHIFT>+<SPACE> or <CTRL>+<SPACE> or else, next to CACHE_CAPACITY=1000.
Sounds a bit profanatory, but I've often enough stumbled upon such things.
Check for spaces in your properties file or try as below
String cacheProp = connectionParameters.getProperty("CACHE_CAPACITY")
//For debug
System.out.println("cacheProp="+cacheProp);
Integer cache = new Integer(cacheProp.trim());
This code worked fine for me i kept the properties file in resources folder(src/main/resources)
public static void MysqlDictionary() {
try {
Properties p = new Properties();
p.load(MyTest.class.getResourceAsStream("/test.properties"));
String host = p.getProperty("MWN_HOSTNAME");
String user = p.getProperty("MWN_USER");
String passwd = p.getProperty("MWN_PASSWD");
String dbname = p.getProperty("MWN_DB");
String cache = p.getProperty("CACHE_CAPACITY");
int i = Integer.parseInt(cache);
System.out.println(host+"\t"+user+"\t"+passwd+"\t"+dbname+"\t"+i);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I write a code to connect to database from servlet.I want to use properties.but it does not work.i think i my code or properties file has problem.please help me to correct it.
try
{
Properties prop=new Properties();
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
prop.load(in);
in.close();
String drivers = prop.getProperty("jdbc.drivers");
String connectionURL = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
Class.forName(drivers);
con=DriverManager.getConnection(connectionURL,username,password);
System.out.println("Connection Successful");
..
and this is my properties file
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#192.168.101.84:1521:orcl
jdbc.username=user1
jdbc.password=123
Instead of
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
use
InputStream in = getClass().getResourceAsStream("dbConnection.properties");
try {
FileReader reader = new FileReader("Full Path");
Properties prop = new Properties();
prop.load(reader);
String drivers = prop.getProperty("jdbc.driverClassName");
String connectionURL = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
Class.forName(drivers);
Connection con = DriverManager.getConnection(connectionURL, username, password);
System.out.println("Connection Successful");
} catch (SQLException sqle) {
// TODO: Add catch code
sqle.printStackTrace();
} catch (FileNotFoundException fnfe) {
// TODO: Add catch code
fnfe.printStackTrace();
} catch (IOException ioe) {
// TODO: Add catch code
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
// TODO: Add catch code
cnfe.printStackTrace();
}catch (Exception e) {
// TODO: Add catch code
e.printStackTrace();
}
This part:
(System.getProperty("WEB-INF/dbConnection.properties"));
is actually referring to your classpath, try removing WEB-INF/ or just leave /, for checking root folder.
Or you can specify the fully qualified name, i.e : "C:\\foo\\test\\...\\dbConnection.properties" or "/app/blah/.../dbConnectionProperties"
For Class name, in the properties file you have defined the driver as 'jdbc.driverClassName'
but when passing variable you just pass as 'jdbc.drivers'
My IDE is Eclipse Indigo. I get this when I was trying to connect:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
And here is my code.
public class TPCH
{
public static void main(String[] args)
{
String userName = "tpch";
String password = "tpch";
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", userName);
connectionProps.put("password", password);
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e)
{
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/",
connectionProps);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("Error connecting to db");
}
}
}
I think JDBC is not imported. I tried to import it by
preference -> java -> build path -> user library -> add jars
But I still got that exception.
That's not how you add JARs to the classpath in Eclipse.
You have to right-click on your project, select Java Build Path > Libraries and add a JAR file. For MySQL, you'd need the MySQL Connector J.
how can I place my mysql database url, username and password in a file and how can I access them to use in my java code instead of hard coding them. I've tried google but am not getting clear direction
Create a properties file. You can load it by the Properties API.
E.g. config.properties:
url = jdbc:mysql://localhost:3306/dbname
username = foo
password = bar
Then you can load and read it as follows (after you've placed it in the classpath):
Properties config = new Properties();
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
String url = config.getProperty("url");
String username = config.getProperty("username");
String password = config.getProperty("password");
// ...
/**
* Function that connects to a DB and data fro connection is loaded from a properties file
* #param fileName
* #return the connection to DB or null if any problem
*/
public java.sql.Connection connect_to_database_from_properties(String fileName)
{
Properties prop = new Properties();
InputStream is;
try {
is = new FileInputStream(fileName);
prop.load(is);
String url=prop.getProperty("url");
String un=prop.getProperty("username");
String pass=prop.getProperty("password");
System.out.println("URL: "+url+" UN: "+un+" PASS: "+pass);
is.close();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conection =DriverManager.getConnection(url, un, pass);
return conection;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I need to initialize a DataSource given url and driver.
Its need to be generic enough to support Oracle and SQL Server.
the app is running on jboss 5.
provided sample for both:
<db-connection name="TEST-ORACLE">
<url>jdbc:oracle:thin:#test:1521:ins1</url>
<driver>oracle.jdbc.xa.client.OracleXADataSource</driver>
<user>user</user>
<password>{ENCR}oRloKFKlqXs=</password>
<min-size>5</min-size>
<max-size>30</max-size>
<idle-timeout-minutes>1</idle-timeout-minutes>
</db-connection>
<db-connections>
<db-connection name="TEST-MSSQLSERVER">
<url>jdbc:jtds:sqlserver://server:1433/db;ProgramName=program;SelectMethod=cursor;useLOBs=false</url>
<driver>net.sourceforge.jtds.jdbc.Driver</driver>
<user>user</user>
<password>{ENCR}oRloKFKlqXs=</password>
<min-size>40</min-size>
<max-size>80</max-size>
<idle-timeout-minutes>1</idle-timeout-minutes>
</db-connection>
The OracleXADataSource is implementing the inteface DataSource so its quit easy... but im not sure that generic enough.
EDIT
I wonder what should be the way to achive that if i have multipile db connections and multipile instances / schemas in those connections.....
my current code looks like:
private DataSource getDataSourceForTanent(TenantConfig i_Tenant) {
DataSource result = null;
ClassLoader loader = DBConnector.class.getClassLoader();
try {
Class driverClass = loader.loadClass(i_Tenant.getDriver());
Object driver = driverClass.newInstance();
if(driver instanceof OracleDataSource){
((OracleDataSource)driver).setURL(i_Tenant.getUrl());
((OracleDataSource)driver).setUser(i_Tenant.getUser());
((OracleDataSource)driver).setPassword(i_Tenant.getPassword());
result = (DataSource) driver;
} else if(driver instanceof Driver){
Properties prop = new Properties();
prop.put("user", i_Tenant.getUser());
prop.put("password", i_Tenant.getPassword());
prop.put("min-size", i_Tenant.getMinSize());
prop.put("max-size", i_Tenant.getMaxSize());
prop.put("idle-timeout-minutes", i_Tenant.getIdleTimeoutMinute());
Connection con = ((Driver)driver).connect(i_Tenant.getUrl(), prop);
if(con != null){
//TODO: SQLServer handling
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
TenantConfig is a java bean holding the xml properties.
Here's a generic code snippet to get a DataSource by JNDI name:
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/mydatasource");
But from your XML file I am not sure what the JNDI name is. What XML dialect is it?