snake case for column names in phantom-dsl - phantom-dsl

Im trying to use this library for an existing application that already have records in cassandra and it table columns are written in snake case. Is there a way to have my phantom model objects in snake case.

Just override column name:
abstract class User extends Table[...] {
object lastName extends StringColumn {
override val name: String = "last_name"
}
}

Have a look here, at the official documentation.
import com.outworkers.phantom.NamingStrategy.SnakeCase.caseSensitive
import com.outworkers.phantom.NamingStrategy.SnakeCase.caseInsensitive
There is also a test suite that might be of help, but you need to import this in every file where you define tables. Tests are here.

Related

Find by id=1 spring data jpa

I have a table component and entity Component. I want to select id = 1 record from jpa query. Can I write 'findByIdOne' or 'findByIdEqualtoOne'? will that give me id = 1 record? Please let me know, Thanks.
No, you cannot. Refer to the Spring Data JPA documentation which documents the exact keywords that you can use.
You are free to specify the query that you want a method to execute though. Something like
#Query("select c from Component c where c.id=1")
Component findByIdOne();
I do have to put a disclaimer: by providing this solution I assume that you are really sure that ID 1 is always going to exist and will always point to exactly the same Component record in any environment that you may be running the application against. Hardcoded database IDs in your application code is not something I would ever recommend.
Direct writing the query dsl you cant, but there is a 'way' with Java 8 using default methods:
Let's say you have the query:
public interface ComponentRespository extends CrudRepository<Component, Long> {
#Query("select c from Component c where c.id=:id")
Component findById(#Param("id") Long id);
default Component findByIdOne() {
return findById(1L);
}
//eventually
default Component findByIdTwo() {
return findById(2L);
}
}
This way you can use:
private ComponentRespository componentRepository;
.....
Component componentOne = componentRepository.findByIdOne();
Component componentTwo = componentRepository.findByIdTwo();
You can use Optional<EntityName> findById(long id) or List<EntityName> findById(long id) if it's not unique.
You can use Optional<EntityName> findById(long id) or List<EntityName> findAllById if it's not unique.
We have several options:
findByIdIs(long id) or findByIdEquals(long id)

How to connect three tables using only one entity/class in Spring & Hibernate

I have only one entity which is School - a class (example). I have 7 fields in there and those fields are from 3 different tables. The first table for example is called Classroom, second is the Teachers, third is Subject. The teachers and subject table are connected by a pk: subject_id while the classroom table and teachers table are connected by classroom_id.
I tried secondary tables but it looks like it's not correct. How to connect those tables inside a single entity and write a query in the DAO IMPLementation
You should use Entity per Table.
If you need to select into non database related Model class, you can be done easily with spring-data-jpa.
After create the Model class (like School) just use the following sample to query:
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) " +
"from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}
In this example the programmer has an address field (OneToOne), but you can create any kind of query, the important thing here is the constructor call of the model.
If you want to use plain sql or impl class instead of interface to query, you can use Spring's RowMapper too.
class ProgrammerNameAndCity{
fields...
allArgConstructor...
}
public interface ProgrammerRepository extends JpaRepository<Programmer,Long> {
#Query(" select new com.zlrx.database.pojo.ProgrammerNameAndCity(p.name,p.address.city) "
+ "from Programmer p where p.idNumber=?1")
ProgrammerNameAndCity findNameAndCityByIdNumber(String idNumber);
}

Laravel Query builder and table names

I noticed that I write the database table names quite a lot, and in different files, when I use the Query Builder. If I were to change the database table names, I would have to search and change quite many rows in my project.
Is this an issue your Laravel guys noticed and come up with an solution to?
I like the Eloquent approach which uses class models, instead of database names; but for some queries I think the Query Builder is a better solution (though I am no expert in this matter).
If you already have a queryBuilder object you can obtain the table name like
$tableName = $query->getModel()->getTable();
Use this in your query :
(new YourModel())->getTable()
Example :
DB:raw('SELECT * FROM '.(new User())->getTable().' WHERE id=3');
How about using OOP concept. Laravel is a framework, so no one stops you from using basic PHP OOP concept. This is what I do:
Consider my query is like :
$result=DB::table('myTable')->select()->get();
What I do is make a class that holds all the tablenames :
class TableName
{
private $tableName= "myTable";
public function getTableName()
{
return $this->tableName;
}
public function setTableName($table_name)
{
$this->tableName = $table_name;
}
}
Now all i have to do is call a method using an object in the file I want to use the table like :
$name = new TableName() ;
$result=DB::table($name->getTableName())->select()->get();
Use wherever you want. I don't think its the best solution however it works for me. Hope it helps
Maybe you can extend the model class.
CModel extend Model {
protected static $tableName;
public static getTableName(){
if(static::$tableName)
return static::$tableName;
/* if you create a "reference break" you don't have to *
/* create "protected static $tableName" row in your all model */
$table = (new static())->getTable();
return static::$tableName = &$table;
}
}
YourModel extends CModel {...}
than you can use
YourModel::getTableName()
I'm not have better idea.

Propel auto generated classes

I have given a project that is written in codeIgnotor and Propel 1.6 as ORM. The only ORM I have used is Eloquent so its really confusing for me to see all these classes in Propel.
When I run propel bat file with defined schema I get three classes e.g
For user I get
1 - User.php extends BaseUser
2 - UserPeer.php extends BaseUserPeer
3 - UserQuery.php extends BaseUserQuery
According to propel documentation Peer Class is for backward compatibility what does that mean.
And also If some one could please explain what type of fuctions one would define inside each class.
Also there is om folder in auto generated build. Is it a good idea to add your method inside these classes.
Any help would be realllly appreciated. If someone could use User example to explain.
Here's a very good Propel article for that: Propel By Example
User.php represents a row in the User table, and your query/update logic in UserQuery.php
The om folder contains class definitions from which your "User" is extended, so don't touch the folder, it gets overwritten everytime you build your model
Examples for #2 above:
Scenario #1: When a User is updated, set TimeUpdated column to the unix current time.
Scenario #2: You want be able to get a Users Full Name
Implementation:
<?php
class User extends BaseUser
{
public function preUpdate(PropelPDO $oConn=null)
{
$this->setTimeUpdated(time());
return true;
}// Will be executed everytime you call '->save()' on an existing row
public function getName()
{
return $this->getFirstName() . ' ' . $this->getLastName();
}
...
Usage for scenario #2:
$User = UserQuery::create()->findPk(1);
echo 'FirstName: ' . $User->getName();
Scenario #3: You want to add a filter for Male teen users
Implementation:
<?php
class UserQuery extends BaseUserQuery
{
public function MaleTeen()
{
return $this
->filterByGender('M')
->filterByAge([
'min' => 13,
'max' => 19
]);
}
...
Usage: $Teens = UserQuery::create()->MaleTeen()->find(); // Did someone say D.R.Y?
I hope it helps.

How can I configure Grails id columns to use UUID on Oracle?

I'd like to use a 128-bit UUID rather than Long for the id field on all of my Grails domains. I'd rather not have to specify all of the mapping information on every domain. Is there a simple way to achieve this in a generic/global way? I'm using Grails 2.3.x, the Hibernate 3.6.10.2 plugin, the Database Migration Plugin 1.3.8, and Oracle 11g (11.2.0.2.0).
There seem to be a number of questions related to this, but none provide complete, accurate, and up-to-date answers that actually work.
Related Questions
What's the best way to define custom id generation as default in Grails?
grails using uuid as id and mapping to to binary column
Configuring Grails/Hibernate/Postgres for UUID
Problems mapping UUID in JPA/hibernate
Custom 16 digit ID Generator in Grails Domain
Using UUID and RAW(16)
If you want to use a UUID in your Grails domain and a RAW(16) in your database, you'll need to add the following.
For every domain, specify the id field. Here's an example using ExampleDomain.groovy
class ExampleDomain {
UUID id
}
Add the following mapping to Config.groovy
grails.gorm.default.mapping = {
id(generator: "uuid2", type: "uuid-binary", length: 16)
}
For details on the three values I've selected, please see these links.
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#d0e5294
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/types.html#types-basic-value-uuid
How should I store a GUID in Oracle?
Add a custom dialect to your data source entry in Datasource.groovy. If you are using Hibernate 4.0.0.CR5 or higher, you can skip this step.
dataSource {
// Other configuration values removed for brevity
dialect = com.example.hibernate.dialect.BinaryAwareOracle10gDialect
}
Implement the custom dialect you referenced in step #3. Here is BinaryAwareOracle10gDialect implemented in Java. If you are using Hibernate 4.0.0.CR5 or higher, you can skip this step.
package com.example.hibernate.dialect;
import java.sql.Types;
import org.hibernate.dialect.Oracle10gDialect;
public class BinaryAwareOracle10gDialect extends Oracle10gDialect {
#Override
protected void registerLargeObjectTypeMappings() {
super.registerLargeObjectTypeMappings();
registerColumnType(Types.BINARY, 2000, "raw($l)");
registerColumnType(Types.BINARY, "long raw");
}
}
For more information about this change, please see the related Hibernate defect https://hibernate.atlassian.net/browse/HHH-6188.
Using UUID and VARCHAR2(36)
If you want to use a UUID in your Grails domain and a VARCHAR2(36) in your database, you'll need to add the following.
For every domain, specify the id field. Here's an example using ExampleDomain.groovy.
class ExampleDomain {
UUID id
}
Add the following mapping to Config.groovy
grails.gorm.default.mapping = {
id(generator: "uuid2", type: "uuid-char", length: 36)
}
For details on the three values, please see the links in step #2 from the previous section.
I think there is a easy way:
String id = UUID.randomUUID().toString()
static mapping = {
id generator:'assigned'
}

Resources