I have a table in mysql database which consists of 3 columns: ID (int and primary key), name and surname (both are strings).
Now I created a model class in scala:
class Clients(
ID: Int,
NAME: String,
SURNAME: String
)
and in main function I have this code which connects me to db:
val db = Database.forConfig("scalaTest")
and my application.conf looks like this:
scalaTest = {
url = "jdbc:mysql://localhost/Scala1"
user = "root"
password = "mysql"
driver = com.mysql.jdbc.Driver
connectionPool = disabled
keepAliveConnection = true
}
And I am supposed to use slick framework to make connection between my scala program and database.
Now I am wondering if I created my model well, or should it look different? Also, I do not know how to connect my model class to database, I've seen few code samples (even the hello_slick_3.0 which is a demo of how to use slick for this purpose), but I did not understand those.
Any help would be appreciated.
You also need to define a table model. You can check a full fledged example here:
Gist for Slick 3.1.0 with scala.
The example is for H2(in memory database but slick abstracts the DB away. It's done exactly the same way for any underlying DB.
Related
I am very new to nodejs and trying to create a registration API using nodejs, I search for it and got some code but the problem is developer is using MongoDB but I am using MYSQL. So my question is how to create a schema in MYSQL using nodejs, I got the code where developer created the schema in MongoDB.
Here is the code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: String,
password: String,
});
module.exports = mongoose.model('user', userSchema, 'users');
Also Why we need schema in the first place can't I just create table in my database manually and Insert data using Insert Query.
Thanks.
You don´t need a specific schema if you are using mySQL. The database itself has a schema and won´t give you the chance to store malformed data if configured correctly. Mongoose provides a schema for mongoDB, because mongoDB is schema-less. You can store any kind of data and you won´t get an error back if malformed data was stored.
But of course if you are using TypeScript, you can build an interface or a class and validate data before storing without the use of any kind of third-party package
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.
development environment
Lnaguage : Golang ver.1.9.2
DB : mySQL
Framework : not decided (Maybe I'll use revel)
situation
I already have DB which has singular-name table ,like "user", "page". It can't be changed.
Now I'll develop new application using this DB.
I created simple application to connect this DB, and tried to auto migrate using gorm(https://github.com/jinzhu/gorm).
I defined some models, like "user" which is same as existing DB table name, and run auto-migrate just as it written in (http://jinzhu.me/gorm/database.html#connecting-to-a-database )
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
Then, new table "users" was created.
Question
Can I create singular-name table, like "user" with auto-migrate or those things ?
Using gorm is not required, so I'll use another orm library if it works.
I hope anyone help me !
Implement function TableName on struct User to return a custom name for the table. The ORM uses this function to get the table name for all DB operations.
func (user *User) TableName() string {
return "user"
}
Refer docs here: http://jinzhu.me/gorm/models.html#table-name-is-the-pluralized-version-of-struct-name
You have set with db instance to use singular table, like this:
db.SingularTable(true)
I am trying to generate schema from the DataNucleus SchemaTool for a mysql database, that will store countries and states. Here is a sample of that code:
#PersistenceCapable
Public class State{
private String shortCode;
private String fullName;
#Column(allowsNull = "true",name="country_id")
private Country countryId;
}
The following are my schemaGeneration properties:
datanucleus.ConnectionDriverName=com.mysql.jdbc.Driver
datanucleus.ConnectionURL=jdbc:mysql://localhost:3306/geog
datanucleus.ConnectionUserName=geog
datanucleus.ConnectionPassword=geogPass
datanucleus.schema.validateTables=true
datanucleus.mapping.Catalog=geog
datanucleus.mapping.Schema=geog
In my Country class as well, I have a mapping from a Collection, so that the FK reference for States to the Country table is built correctly.
But there is one problem. In the SQL script generated, the Index part has the Schema name as part of the index name itself, which fails the entire script. Here is that piece:
CREATE INDEX `GEOG`.`MST_STATE_N49` ON `GEOG`.`MST_STATE` (`COUNTRY_ID`);
Notice the schema name in the GEOG.MST_STATE_N49 part of the index' name.
I tried setting the schema and catalog name to blank but that yields a ''.MST_STATE_N49 which still fails.
I am using MySQL Server 5.7.17 using the 5.1.42 version of the JDBC driver (yes, not the latest) on Data nucleus JDO 3.1
Any hints on how I can get rid of the schema/catalog name in the generated DDL?
Why are you putting "datanucleus.mapping.Schema" when using MySQL ? MySQL doesnt use schema last I looked. Similarly the "datanucleus.mapping.Catalog" is effectively defined by your URL! MySQL only actually supports JDBC catalog, mapping on to "database", as per this post. Since DataNucleus simply uses the JDBC driver then catalog is the only useful input.
Consequently removal of both schema and catalog properties will DEFAULT to the right place.
After the comment above from Neil Stockton, I commented out both the properties and it worked. Effectively, this is what is needed:
datanucleus.ConnectionDriverName=com.mysql.jdbc.Driver
datanucleus.ConnectionURL=jdbc:mysql://localhost:3306/geog
datanucleus.ConnectionUserName=geog
datanucleus.ConnectionPassword=geogPass
datanucleus.schema.validateTables=true
Hopefully, I can get the answer to the other question (Pt. 2 in my reply-comment above) as well.
Is there a way to recreate an EntityManagerFactory already used in a webapplication at runtime? What I want is tell the entityManagerFactory to forget the last database connection and connect to a new schema at runtime when the webuser selects an other database (mysql schema). Or not forget the already used one but also use a new connection to a different mysql schema which was not used yet. These schemas have the exact same structure (tables, etc.) but for different users for security and other reasons. Is this possible?
I am using the Vaadin framework, Eclipselink 2.4.1, Mysql 5.5 and Tomcat 7. What I found related to my situation and what I tried already are followings. I am using an Eclipselink composite persistence unit, the second member is always the same, I want to change the first schema for example to "42_candidate" when the user selects the 42nd candidate on the webpage after an other schema was already connected like "41_candidate".
private static EntityManager createEntityManagerForCandidateSchema(String candidateSchemaName) throws javax.persistence.PersistenceException {
System.out.println("createEntityManagerForCandidateSchema called");
// set persistence unit properties
HashMap<String,String> candidatePuProps = new HashMap<String,String>();
candidatePuProps.put("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/"+candidateSchemaName+"?useUnicode=true&characterEncoding=UTF-8");
HashMap<String,Map> compositePuProps = new HashMap<String,Map>();
compositePuProps.put("election_model_candidate", candidatePuProps);
Map puProps = new HashMap();
puProps.put("eclipselink.logging.level", "FINEST");
puProps.put("eclipselink.composite-unit.properties", compositePuProps);
// puProps.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, "com.beharbe.ui.ElectionSessionCustomizer");
boolean candidateDatabaseSchemaNotFound = false;
try {
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("election_composite_pu",puProps);
emf.close(); // to forget latest things
emf = javax.persistence.Persistence.createEntityManagerFactory("election_composite_pu",puProps);
EntityManager em = emf.createEntityManager(compositePuProps);
...
public void selectionChanged(int newCandidatePersonId) {
entityManager = Util.createEntityManagerForCandidateSchema(newCandidatePersonId);
...
(Eclipselink Composite PU)
wiki.eclipse.org/EclipseLink/UserGuide/sandbox/gelernter/Composite_Persistence_Units#Persistence_Unit_Properties
(Dynamic Persistence)
dev.eclipse.org/svnroot/rt/org.eclipse.persistence/branches/2.1/trunk/examples/jpa.employee/eclipselink.example.jpa.employee.dynamic/src/example/Main.java
(EclipseLink - How to configure Database Schema name at runtime)
www.rqna.net/qna/kxvmwy-jpa-eclipselink-how-to-configure-database-schema-name-at-runtime.html
(Eclipselink with Tomcat tutorial)
wiki.eclipse.org/EclipseLink/Examples/JPA/Tomcat_Web_Tutorial#Session_Customizer
(Using JPAContainer with Hibernate (Vaadin))
vaadin.com/book/-/page/jpacontainer.hibernate.html
(How can I make a JPA application access different databases?)
stackoverflow.com/questions/9315593/how-can-i-make-a-jpa-application-access-different-databases
(Connect two or more databases dynamically)
stackoverflow.com/questions/9732750/connect-two-or-more-databases-dynamically?lq=1
(JPA - Using Multiple data sources to define access control)
www.rqna.net/qna/kqqihk-jpa-using-multiple-data-sources-to-define-access-control.html
JPA2 run-time database connection
JPA - EclipseLink - How to configure Database Schema name at runtime (Eclipselink SessionCustomizer)
Maybe I should do it somehow with the EclipseLink SessionCustomizer? (see latest link)
thanks for any help in advance
Meanwhile I found something, this can be what I have to use:
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Auditing
I am trying this way but it still connects to the schema which was connected first when the EMF called first time:
....
candidatePuProps.put(PersistenceUnitProperties.JDBC_URL, "jdbc:mysql://localhost:3306/"+candidateSchemaName+"?useUnicode=true&characterEncoding=UTF-8");
candidatePuProps.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_MODE, "Always");
candidatePuProps.put(PersistenceUnitProperties.EXCLUSIVE_CONNECTION_IS_LAZY, "false");
...
If you want to access two different databases/schemas, you can just call createEntityManagerFactory() passing a properties map with your new connection.
To set the schema with EclipseLink in code you can set the tableQualifier in a Customizer. To get a new EntityManagerFactory you can pass the "eclipselink.session-name" property.
Your code looks correct. What version of EclipseLink are you using?
Remove the composite persistence unit, I think you seem to just want to connect to a different database. Composite persistence units are for when you have relationships across databases.