Firstly, is this is a good idea (to generate/use pojo with default constructor and setters) ?
If yes, how is it possible by using the code generator ?
I'm using the nu.studer.jooq Gradle plugin (https://github.com/etiennestuder/gradle-jooq-plugin) with jooq 3.11.9 and a postgres db.
// Generator
jooq {
version = '3.11.9'
edition = 'OSS'
sample(sourceSets.main) {
jdbc {
driver = 'org.postgresql.Driver'
url = 'jdbc:postgresql://localhost:5432/mydb'
user = 'myuser'
password = 'mypwd'
// properties {
// property {
// key = 'ssl'
// value = 'true'
// }
// }
}
generator {
name = 'org.jooq.codegen.DefaultGenerator'
strategy {
name = 'org.jooq.codegen.DefaultGeneratorStrategy'
}
database {
name = 'org.jooq.meta.postgres.PostgresDatabase'
inputSchema = 'public'
forcedTypes {
forcedType {
name = 'varchar'
expression = '.*'
types = 'JSONB?'
}
forcedType {
name = 'varchar'
expression = '.*'
types = 'INET'
}
}
}
generate {
relations = true
deprecated = false
records = true
immutablePojos = true
fluentSetters = true
}
target {
packageName = 'com.project.generated'
directory = 'src/main/java'
}
}
}
}
Thank in advance for your ideas and advices.
Firstly, is this is a good idea (to generate/use pojo with default constructor and setters) ?
A good idea for doing what? The jOOQ code generator doesn't judge you. Using default constructors and getters/setters is one supported flavour. Immutable POJOs is the other one.
If yes, how is it possible by using the code generator ?
Turn off the genreation of immutablePojos
pojos = true
immutablePojos = false
Note that you don't have to turn that off. The default is for them to be turned off.
I just released a code generator which does exactly what you want. (If i got you right)
Try https://github.com/carstenSpraener/cgV19 ist has a PoJo generator in it's HelloWorld exammple. Supports
gradle plugin
modular model loader
"cartridges" for different needs:
cartridgeA: PoJo in Java
cartridgeB: PoJo in TypeScript
Related
I'm using JIB (not super relevant) and I want to pass in variables from command line in my deployment script.
I append using -PinputTag=${DOCKER_TAG} -PbuildEnv=nonprod in my gradle command, which is cool. But when it's missing, I want that ternary to kick in.
I'm getting the error:
Could not get unknown property 'inputTag' for project ':webserver' of type org.gradle.api.Project.
def inputTag = inputTag ?: 'latest'
def buildEnv = buildEnv ?: 'nonprod'
jib {
container {
mainClass = 'com.example.hi'
}
to {
image = 'image/cool-image'
tags = ['latest', inputTag]
}
container {
creationTime = 'USE_CURRENT_TIMESTAMP'
ports = ['8080']
jvmFlags = ['-Dspring.profiles.active=' + buildEnv]
}
}
Found Solution
def inputTag = project.hasProperty('inputTag') ? project.property('inputTag') : 'latest'
def buildEnv = project.hasProperty('buildEnv') ? project.property('buildEnv') : 'nonprod'
This seems to be working, is this the best way?
How about this?
image = 'image/cool-image:' + (project.findProperty('inputTag') ?: 'latest')
Note jib.to.tags are additional tags. jib.to.image = 'image/cool-image' already implies image/cool-image:latest, so no need to duplicate latest in jib.to.tags.
I am trying to use some Java RHS to get the string value of dependent tokens using Stanford dependency parser in GATE, and add them as features of a new annotation.
I am having problems targeting just the 'dependencies' feature of the token, and getting the string value from the tokenID.
Using below specifying only 'depdencies' also throws a java null pointer error:
for(Annotation lookupAnn : tokens.inDocumentOrder())
{
FeatureMap lookupFeatures = lookupAnn.getFeatures();
token = lookupFeatures.get("dependencies").toString();
}
I can use below to get all the features of a token,
gate.Utils.inDocumentOrder
but it returns all features, including the dependent tokenID's; i.e:
dependencies = [nsubj(8390), dobj(8394)]
I would like to get just the dependent token's string value from these tokenID's.
Is there any way to access dependent token string value and add them as a feature to the annotation?
Many thanks for your help
Here is a working JAPE example. It only printns to the GATE's message window (std out), It doesn't create any new annotations with features you asked for. Please finish it yourself...
Stanford_CoreNLP plugin has to be loaded in GATE to make this JAPE file loadable. Otherwise you will get class not found exception for DependencyRelation class.
Imports: {
import gate.stanford.DependencyRelation;
}
Phase: GetTokenDepsPhase
Input: Token
Options: control = all
Rule: GetTokenDepsRule
(
{Token}
): token
-->
:token {
//note that tokenAnnots contains only a single annotation so the loop could be avoided...
for (Annotation token : tokenAnnots) {
Object deps = token.getFeatures().get("dependencies");
//sometimes the dependencies feature is missing - skip it
if (deps == null) continue;
//token.getFeatures().get("string") could be used instead of gate.Utils.stringFor(doc,token)...
System.out.println("Dependencies for token " + gate.Utils.stringFor(doc, token));
//the dependencies feature has to be typed to List<DependencyRelation>
List<DependencyRelation> typedDeps = (List<DependencyRelation>) deps;
for (DependencyRelation r : typedDeps) {
//use DependencyRelation.getTargetId() to get the id of the target token
//use inputAS.get(id) to get the annotation for its id
Annotation targetToken = inputAS.get(r.getTargetId());
//use DependencyRelation.getType() to get the dependency type
System.out.println(" " +r.getType()+ ": " +gate.Utils.stringFor(doc, targetToken));
}
}
}
I am using below code and found filed against category object but there I am not able to find the value. Please help.
IProjectAreaHandle projectAreaHandle = workItem.getProjectArea();
IAttribute someAttribute = workItemClient.findAttribute(projectAreaHandle, IWorkItem.CATEGORY_PROPERTY,
monitor);
IAttributeHandle iAttributeHandle = (IAttributeHandle) someAttribute;
IAttribute iAttribute = (IAttribute) repo
.itemManager().fetchCompleteItem(
iAttributeHandle, IItemManager.DEFAULT ,monitor);
Object value = workItem.getValue(iAttribute);
Below code will help to find out the filed against attribute value :
ICategoryHandle iCategoryHandle = workItem.getCategory();
ICategory iCategory1 = (ICategory) repo
.itemManager().fetchCompleteItem(
iCategoryHandle, IItemManager.DEFAULT ,monitor);
return iCategory1.getName();
Is there a way to build SQL in phases/stages using jOOQ? Something like:
DSLContext create = DSL.using(conn, SQLDialect.MYSQL);
DSL dsl = create.from(table("links"));
if( !StringUtils.isEmpty(place) ) { // place is specified, change the query
long placeId = getPlaceId();
if (placeId > 0) {
dsl = create.from(table("place_links"))
.join(table("links"))
.on(field("links.id").equal(field("place_links.link_id")))
.where(field("place_links.place_id").equal(placeId));
}
}
String sql = dsl.select(field("*"))
.orderBy("links.score")
.limit(1)
.getSQL();
The above won't compile but I am looking for something on similar principles. I need to start with from since the target table changes at runtime.
The requirement is that the final query changes at runtime depending on values which are fed in.
SQL doesn't feel like a very composable language if you start constructing the SELECT statement right away. But if you think of the different clauses as being the dynamic building blocks, things immediately become a lot simpler. In your case:
Table<?> from = table("links");
Condition where = trueCondition();
if (!StringUtils.isEmpty(place)) {
long placeId = getPlaceId();
if (placeId > 0) {
from = from.join("place_links").on("links.id = place_links.link_id");
where = where.and("place_links.place_id = ?", placeId);
}
}
DSL.using(conn)
.selectFrom(from)
.where(where)
.orderBy(field("links.score"))
.limit(1)
.fetch();
The above is assuming this
import static org.jooq.impl.DSL.*;
More about how to build SQL statements dynamically with jOOQ is described here:
http://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql
I am trying to use querydsl for building dynamic queries for dynamic schemas. I am trying to get just the query instead of having to actually execute it.
So far I have faced two issues:
- The schema.table notation is absent. Instead I only get the table name.
- I have been able to get the query but it separates out the variables and puts '?' instead which is understandable. But I am wondering if there is some way to get fully materialized query including the parameters.
Here is my current attempt and result(I am using MySQLTemplates to create the configuration):
private SQLTemplates templates = new MySQLTemplates();
private Configuration configuration = new Configuration(templates);
String table = "sometable"
Path<Object> userPath = new PathImpl<Object>(Object.class, table);
StringPath usernamePath = Expressions.stringPath(userPath, "username");
NumberPath<Long> idPath = Expressions.numberPath(Long.class, userPath, "id");
SQLQuery sqlQuery = new SQLQuery(connection, configuration)
.from(userPath).where(idPath.eq(1l)).limit(10);
String query = sqlQuery.getSQL(usernamePath).getSQL();
return query;
And what I get is:
select sometable.username
from sometable
where sometable.id = ?
limit ?
What I wanted to get was:
select sometable.username
from someschema.sometable
where sometable.id = ?
limit ?
Update: I came up with this sort of hack to get parameters materialized(Not ideal and would love better solution) But still could not get Schema.Table notation to work:
Hack follows. Please suggest cleaner QueryDsl way of doing it:
String query = cleanQuery(sqlQuery.getSQL(usernamePath));
private String cleanQuery(SQLBindings bindings){
String query = bindings.getSQL();
for (Object binding : bindings.getBindings()) {
query = query.replaceFirst("\\?", binding.toString());
}
return query;
}
To enable schema printing use the following pattern
SQLTemplates templates = MySQLTemplates.builder()
.printSchema()
.build();
SQLTemplates subclasses were used before, but since some time the builder pattern is the official way to customize the templates http://www.querydsl.com/static/querydsl/3.3.1/reference/html/ch02s03.html#d0e904
And to enable direct serialization of literals use
//configuration level
configuration.setUseLiterals(true);
//query level
configuration.setUseLiterals(true);
Here is a full example
// configuration
SQLTemplates templates = MySQLTemplates.builder()
.printSchema()
.build();
Configuration configuration = new Configuration(templates);
// querying
SQLQuery sqlQuery = new SQLQuery(connection, configuration)
.from(userPath).where(idPath.eq(1l)).limit(10);
sqlQuery.setUseLiterals(true);
String query = sqlQuery.getSQL(usernamePath).getSQL();
If you always just want the SQL query string out, move setUseLiterals from query to configuration.
Concerning the usage of Querydsl expressions the usage of code generation like documented here is advised http://www.querydsl.com/static/querydsl/3.3.1/reference/html/ch02s03.html
It will make your code typesafe, compact and readable.
If you want to try Querydsl without code generation you can replace
Path<Object> userPath = new PathImpl<Object>(Object.class, variable);
with
Path<Object> userPath = new RelationalPathBase<Object>(Object.class, variable, schema, table);
When working with QueryDSL, you must provide a template for the database platform to build the query for. I see you are already are doing this here:
private SQLTemplates templates = new MySQLTemplates();
private Configuration configuration = new Configuration(templates);
To make the schema name appear in the generated query, the only way I have found to do this is (there may be an easier way) is to extend the template class and explicitly call this.setPrintSchema(true); inside the constructor. Here is a class that should work for MySql:
import com.mysema.query.sql.MySQLTemplates;
public class NewMySqlTemplates extends MySQLTemplates {
public NewMySqlTemplates() {
super('\\', false);
}
public NewMySqlTemplates(boolean quote) {
super('\\', quote);
}
public NewMySqlTemplates(char escape, boolean quote) {
super(escape, quote);
this.setPrintSchema(true);
}
}
Then simply use this NewMySqlTemplates class in place of the MySQLTemplates class like this:
private SQLTemplates templates = new NewMySQLTemplates();
private Configuration configuration = new Configuration(templates);
I have this working using PostgresTemplates, so I may have a typo or mistake in the NewMySqlTemplates class above, but you should be able to get it to work. Good luck!