i'm writing a web application in tapestry.
In my application i want to use friendly urls. Now i'm able to to render the url page like this:
http://localhost:8080/page/page-name
wat i want to do is to render URLs like this:
http://localhost:8080/page-name
All pages are stored on a Postgresql DB.
I'm currently using Tapestry 5.4-beta16 and i've already read the tapestry documentation:
http://tapestry.apache.org/url-rewriting.html
http://blog.tapestry5.de/index.php/2010/09/06/new-url-rewriting-api/
Now, this is the Class for list all pages stored on the DB (Only for test)
public class Pages {
#Inject
private Session session;
#Property
List<it.garuti.tapestrycms.entities.Pagine> pagine;
#Property
private it.garuti.tapestrycms.entities.Pagine pagina;
void setupRender() {
pagine = session.createCriteria(it.garuti.tapestrycms.entities.Pagine.class).list();
}
}
And this is the class for show the page content:
public class Page {
#Property
private Page page;
#Inject
private Logger logger;
#Inject
private Session session;
#Inject
Request request;
#InjectPage
Index index;
#Property
private String slug;
void onActivate(String slug) {
this.slug = slug;
}
Object onActivate() {
if (session.createCriteria(Pagine.class)
.add(Restrictions.eq("slug", slug)).uniqueResult() == null)
return new HttpError(404, "Resource not found");
return null;
}
String onPassivate() {
return slug;
}
void setupRender() {
page = (Pages) session.createCriteria(Pages.class)
.add(Restrictions.eq("slug", slug)).uniqueResult();
}
}
And finally the Entity for Pages:
#Entity
#Table(name = "pages", schema = "public")
public class Pages implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pagine_seq")
#SequenceGenerator( name= "pagine_seq", sequenceName = "pagine_id_seq")
#Column(name = "id", unique = true, nullable = false)
private long id;
#Column(name = "titolo", nullable = false, length = 60, unique = true)
private String titolo;
#Column(name = "slug", nullable = false, length = 60, unique = true)
private String slug;
#Column(name = "contenuto", nullable = false, columnDefinition = "TEXT")
private String contenuto;
#Column(name = "data_creazione", nullable = false)
private Date dataCreazione;
#Column(name = "data_modifica")
private Date dataModifica;
#Column(name = "stato", nullable = false)
private String stato;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "utente_id", nullable = false)
private Users user;
getter and setter...
....
}
Tank You
Lorenzo
There's a special case in tapestry when your page class has the name Index it will not include the page name in the URL. So if you rename the class Page to Index I think you'll achieve what you want without requiring any explicit url rewriting
Related
I have a spring boot project with apache camel (Using maven dependencies: camel-spring-boot-starter, camel-jpa-starter, camel-endpointdsl).
There are the following 3 entities:
#Entity
#Table(name = RawDataDelivery.TABLE_NAME)
#BatchSize(size = 10)
public class RawDataDelivery extends PersistentObjectWithCreationDate {
protected static final String TABLE_NAME = "raw_data_delivery";
private static final String COLUMN_CONFIGURATION_ID = "configuration_id";
private static final String COLUMN_SCOPED_CALCULATED = "scopes_calculated";
#Column(nullable = false, name = COLUMN_SCOPED_CALCULATED)
private boolean scopesCalculated;
#OneToMany(mappedBy = "rawDataDelivery", fetch = FetchType.LAZY)
private Set<RawDataFile> files = new HashSet<>();
#CollectionTable(name = "processed_scopes_per_delivery")
#ElementCollection(targetClass = String.class)
private Set<String> processedScopes = new HashSet<>();
// Getter/Setter
}
#Entity
#Table(name = RawDataFile.TABLE_NAME)
#BatchSize(size = 100)
public class RawDataFile extends PersistentObjectWithCreationDate {
protected static final String TABLE_NAME = "raw_data_files";
private static final String COLUMN_CONFIGURATION_ID = "configuration_id";
private static final String COLUMN_RAW_DATA_DELIVERY_ID = "raw_data_delivery_id";
private static final String COLUMN_PARENT_ID = "parent_file_id";
private static final String COLUMN_IDENTIFIER = "identifier";
private static final String COLUMN_CONTENT = "content";
private static final String COLUMN_FILE_SIZE_IN_BYTES = "file_size_in_bytes";
#ManyToOne(optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = COLUMN_RAW_DATA_DELIVERY_ID)
private RawDataDelivery rawDataDelivery;
#Column(name = COLUMN_IDENTIFIER, nullable = false)
private String identifier;
#Lob
#Column(name = COLUMN_CONTENT, nullable = true)
private Blob content;
#Column(name = COLUMN_FILE_SIZE_IN_BYTES, nullable = false)
private long fileSizeInBytes;
// Getter/Setter
}
#Entity
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#Table(name = RawDataRecord.TABLE_NAME, uniqueConstraints = ...)
public class RawDataRecord extends PersistentObjectWithCreationDate {
public static final String TABLE_NAME = "raw_data_records";
static final String COLUMN_RAW_DATA_FILE_ID = "raw_data_file_id";
static final String COLUMN_INDEX = "index";
static final String COLUMN_CONTENT = "content";
static final String COLUMN_HASHCODE = "hashcode";
static final String COLUMN_SCOPE = "scope";
#ManyToOne(optional = false)
#JoinColumn(name = COLUMN_RAW_DATA_FILE_ID)
private RawDataFile rawDataFile;
#Column(name = COLUMN_INDEX, nullable = false)
private long index;
#Lob
#Type(type = "jsonb")
#Column(name = COLUMN_CONTENT, nullable = false, columnDefinition = "jsonb")
private String content;
#Column(name = COLUMN_HASHCODE, nullable = false)
private String hashCode;
#Column(name = COLUMN_SCOPE, nullable = true)
private String scope;
}
What I try to do is to build a route with apache camel which selects all deliveries having the flag "scopesCalculated" == false and calculate/update the scope variable of all records attached to the files of this deliveries. This should happen in one database transaction. If all scopes are updated I want to set the scopesCalculated flag to true and commit the changes to the database (in my case postgresql).
What I have so far is this:
String r3RouteId = ...;
var dataSource3 = jpa(RawDataDelivery.class.getName())
.lockModeType(LockModeType.NONE)
.delay(60).timeUnit(TimeUnit.SECONDS)
.consumeDelete(false)
.query("select rdd from RawDataDelivery rdd where rdd.scopesCalculated is false and rdd.configuration.id = " + configuration.getId())
;
from(dataSource3)
.routeId(r3RouteId)
.routeDescription(configuration.getName())
.messageHistory()
.transacted()
.process(exchange -> {
RawDataDelivery rawDataDelivery = exchange.getIn().getBody(RawDataDelivery.class);
rawDataDelivery.setScopesCalculated(true);
})
.transform(new Expression() {
#Override
public <T> T evaluate(Exchange exchange, Class<T> type) {
RawDataDelivery rawDataDelivery = exchange.getIn().getBody(RawDataDelivery.class);
return (T)rawDataDelivery.getFiles();
}
})
.split(bodyAs(Iterator.class)).streaming()
.transform(new Expression() {
#Override
public <T> T evaluate(Exchange exchange, Class<T> type) {
RawDataFile rawDataFile = exchange.getIn().getBody(RawDataFile.class);
// rawDataRecordJpaRepository is an autowired interface by spring with the following method:
// #Lock(value = LockModeType.NONE)
// Stream<RawDataRecord> findByRawDataFile(RawDataFile rawDataFile);
// we may have many records per file (100k and more), so we don't want to keep them all in memory.
// instead we try to stream the resultset and aggregate them by 500 partitions for processing
return (T)rawDataRecordJpaRepository.findByRawDataFile(rawDataFile);
}
})
.split(bodyAs(Iterator.class)).streaming()
.aggregate(constant("all"), new GroupedBodyAggregationStrategy())
.completionSize(500)
.completionTimeout(TimeUnit.SECONDS.toMillis(5))
.process(exchange -> {
List<RawDataRecord> rawDataRecords = exchange.getIn().getBody(List.class);
for (RawDataRecord rawDataRecord : rawDataRecords) {
rawDataRecord.setScope("abc");
}
})
;
Basically this is working, but I have the problem that the records of the last partition will not be updated. In my example I have 43782 records but only 43500 are updated. 282 remain with scope == null.
I really don't understand the JPA transaction and session management of camel and I can't find some examples on how to update JPA/Hibernate entities with camel (without using SQL component).
I already tried some solutions but none of them are working. Most attempts end with "EntityManager/Session closed", "no transaction is in progress" or "Batch update failed. Expected result 1 but was 0", ...
I tried the following:
to set jpa(...).joinTransaction(false).advanced().sharedEntityManager(true)
use .enrich(jpa(RawDataRecord.class.getName()).query("select rec from RawDataRecord rec where rawDataFile = ${body}")) instead of .transform(...) with JPA repository for the records
using hibernate session from camel headers to update/save/flush entities: "Session session = exchange.getIn().getHeader(JpaConstants.ENTITY_MANAGER, Session.class);"
try to update over new jpa component at the end of the route:
.split(bodyAs(Iterator.class)).streaming()
.to(jpa(RawDataRecord.class.getName()).usePersist(false).flushOnSend(false))
Do you have any other ideas / recommendations?
I want to have one-to-one uni-directional mapping with 2 child entities using shared primary key. Below are model classes
public class Template implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "templatekey")
Integer templateKey;
#Column(name = "templateid", unique = true)
String templateId;
#OneToOne(cascade = CascadeType.ALL, optional = false)
#PrimaryKeyJoinColumn(name = "templatekey", referencedColumnName = "templatekey")
InstantOfferNoEsp instantOfferNoEsp;
#OneToOne(cascade = CascadeType.ALL, optional = false)
#PrimaryKeyJoinColumn(name = "templatekey", referencedColumnName = "templatekey")
Mobile mobile;
//constructor , setter and getters
}
Child 1 :
public class Mobile implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "templatekey")
Integer templateKey;
String mobileNewUrl;
//constructor , setter and getters
}
Child 2:
public class InstantOfferNoEsp {
#Id
#Column(name = "templatekey")
Integer templateKey;
String offerCodeType;
String headerUrl;
//constructor , setter and getters
}
I want templateKey as PK in all tables. and I am calling templateRepository.save(template); to save all entities at once but its not working and getting ids for this class must be manually assigned before calling save() error.
Any suggestions would be of great help. Thank you.
I was able to do what you want with bidirectional #OneToOne like below:
#Entity
public class Mobile {
#Id
Integer templateKey;
#OneToOne
#MapsId
#JoinColumn(name = "templatekey")
Template template;
// ...
}
#Entity
public class InstantOfferNoEsp {
#Id
Integer templateKey;
#OneToOne
#MapsId
#JoinColumn(name = "templatekey")
Template template;
// ...
}
#Entity
public class Template {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "templatekey")
Integer templateKey;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "template", optional = false)
InstantOfferNoEsp instantOfferNoEsp;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "template", optional = false)
Mobile mobile;
// ...
public void setMobile(Mobile mobile)
{
this.mobile = mobile;
this.mobile.setTemplate(this);
}
public void setInstantOfferNoEsp(InstantOfferNoEsp instantOfferNoEsp)
{
this.instantOfferNoEsp = instantOfferNoEsp;
this.instantOfferNoEsp.setTemplate(this);
}
}
and an example of saving:
Mobile mobile = new Mobile();
mobile.setMobileNewUrl("MOB1");
InstantOfferNoEsp instant = new InstantOfferNoEsp();
instant.setOfferCodeType("INST_OFF1");
Template template = new Template();
template.setTemplateId("TMP1");
template.setInstantOffer(instant);
template.setMobile(mobile);
entityManager.persist(template);
P.S. The following mapping works too, but only if we set Template.templateKey manually.
#Entity
public class Template
{
#Id
// #GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "templatekey")
Integer templateKey;
#OneToOne(cascade = CascadeType.ALL, optional = false)
#JoinColumn(name = "templatekey", insertable = false, updatable = false)
InstantOfferNoEsp instantOfferNoEsp;
#OneToOne(cascade = CascadeType.ALL, optional = false)
#JoinColumn(name = "templatekey", insertable = false, updatable = false)
Mobile mobile;
// ...
}
and an example of saving:
Mobile mobile = new Mobile();
mobile.setMobileNewUrl("MOB1");
InstantOfferNoEsp instant = new InstantOfferNoEsp();
instant.setOfferCodeType("INST_OFF1");
Template template = new Template();
template.setTemplateKey(20);
template.setTemplateId("TMP1");
template.setInstantOffer(instant);
template.setMobile(mobile);
entityManager.persist(template);
Also I would suggest your explicitly specify what generation strategy you want to use (do not use GenerationType.AUTO) and use corresponding object wrapper classes instead of primitive types for #Id fields.
I'm using Spring to develop APIs along with JPA. I'm handling a POST request that accepts #RequestBody as a JSON object that looks like this-
{
"id": "323",
"name": "Sam",
"gpsLocation": {
"latitude": 66.7492558,
"longitude": 97.133258
}
}
And an SQL User Table that has the following columns-
id | name | latitude | longitude
Is there a way in Spring to map this nested json object directly to these table columns?
This is what my User.java and GpsLocation.java entity classes look like right now-
#Table(name = "user")
#Entity
public class UnderObservation {
#Column(name = "name", nullable = false)
private String name;
#Id
#Column(name = "id", nullable = false)
private String userID;
private GpsLocation location;
}
#Entity
public class GpsLocation {
#Column(name = "Latitude", nullable = false)
private Double Latitude;
#Column(name = "Longitude", nullable = false)
private Double Longitude;
}
I'm looking for a way to "flatten/unwrap" GpsLocation class so that it directly fits into the User table instead of having a separate table for GpsLocation.
I can not change the JSON Structure because some other No SQL Databases are using this. Also, I'm new to Spring!
The best practice here is using DTO data transfer object that hold the request body
and map it to the user object using external library like mapstruct, ObjectMapper or even do it manually
the DTO is a pojo Object carries data between processes
Try This way with a Constructor:
#Getter
#Setter
#Table(name = "user")
#Entity
public class UnderObservation {
#Column(name = "name", nullable = false)
private String name;
#Id
#Column(name = "id", nullable = false)
private String userID;
#Column(name = "latitude", nullable = false)
private Double latitude;
#Column(name = "longitude", nullable = false)
private Double longitude;
private GpsLocation location;
UnderObservation(String name, String userID, GpsLocation location) {
this.name = name;
this.userID = userID;
this.location = location;
this.latitude = this.location.getLatitude();
this.longitude = this.location.getLongitude();
}
}
I don't understand why the ids are duplicated (id_msg, id_pers_acct), that's what's in my Springboot log :
select personneco0_.id_pers_acct as id_pers_1_2_0_,
…
from test.person_account personacc0_ where personacc0_.id_pers_acct=?
select messages0_.id_pers_acct as id_pers_5_1_0_,
messages0_.id_msg as id_msg1_1_0_,
messages0_.id_msg as id_msg1_1_1_,
messages0_.content as content2_1_1_,
messages0_.date as date3_1_1_,
messages0_.id_pers_acct_person_account as id_pers_4_1_1_,
messages0_.id_pers_acct as id_pers_5_1_1_
from test.message messages0_ where messages0_.id_pers_acct=?
In my entity PersonAccount i have this code :
#OneToMany(mappedBy = "sender", fetch = FetchType.LAZY)
public Set<Message> messages = new HashSet <Message>();
In my entity Message i have this code :
#Entity
#Table(name = "MESSAGE", catalog = "TEST")
public class Message implements Serializable{
/**
*
*/
private static final long serialVersionUID = -602563072975023074L;
#Id
#GeneratedValue
#Column(name = "ID_MSG")
Long idMsg;
#Column(name = "CONTENT")
String content;
#Column(name = "DATE")
Date date;
#Column(name = "ID_PERS_ACCT", nullable = false)
Long sender;
#Column(name = "ID_PERS_ACCT_PERSON_ACCOUNT", nullable = false)
Long receiver;
In my RestController, i call this :
#RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public PersonAccount getUser(#PathVariable Long id) {
return userRepository.getOne(id);
}
I am trying to map the classic bi-directional oneToMany using eclipselink.
My problem is that when i want to insert a new 'child' i get
SQLIntegrityConstraintViolationException.
The database is described like this :
#Entity
#IdClass(KuponPK.class)
#Table(name = "KUPON", schema = "POST", catalog = "")
public class Kupon implements Serializable {
private Integer id;
private String spil;
private Collection<Kombination> kombinationList;
#OneToMany(mappedBy = "kupon", cascade = CascadeType.PERSIST)
public Collection<Kombination> getKombinationList() {
return kombinationList;
}
public class KuponPK implements Serializable {
private Integer id;
private String spil;
#Id
#Column(name = "ID", nullable = false, insertable = true, updatable = true, precision = 0)
public Integer getId() {
return id;
}
#Id
#Column(name = "SPIL", nullable = false, insertable = true, updatable = true, length = 5)
public String getSpil() {
return spil;
}
#Entity
#Table(name = "KOMBINATION", schema = "POST", catalog = "")
public class Kombination {
private Integer id;
private String sorteringOrden;
private Integer sorteringNr;
private Integer antalSpillede;
private BigDecimal odds;
private Kupon kupon;
#ManyToOne
#JoinColumns({#JoinColumn(name = "KUPON_ID", referencedColumnName = "ID", nullable = false, insertable=false, updatable=false),
#JoinColumn(name = "KUPON_SPIL", referencedColumnName = "SPIL", nullable = false, insertable=false, updatable=false)})
public Kupon getKupon() {
return kupon;
}
In my stateless session i have a Kupon object and i create a new Kombination where i set the Kupon and try to merge, but im getting
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("KOMBINATION"."KUPON_ID")
which is obvious since its part of primary key
I am setting the Kombination to Kupon and the Kupon to Kombination, but that doesnt make any difference
How can can i tell that the key is inside the Kupon object which im setting in the Kombination object ??