In my grails application I have an sql query that selects column data from 1 database based on a column in another database.
Thus it is interacting with 2 databases in the SAME query.
Is there a way to pick data from 1 database based on data retrived from another database.
In a scenario like this, how would you put down the code.
Thoughts?
Found a way through.
Created 2 domain objects, Cdisc and Tape.
cdisc and tape are 2 tables in 2 different databases. Both the tables have a common primary Id, player_id.
The idea is to display data from these 2 tables on one page.
Cdisc.groovy
package tune
class Cdisc {
String name
double cId
String id
static mapping = {
table 'cdisc'
version false
columns {
id column:'player_id'
cId column:'c_id'
name column: 'name'
}
}
}
Tape.groovy
package tune
class tape {
String id
String tapeDate
String comments
static mapping = {
table 'tape'
version false
columns {
id column:'player_id'
tapeDate column:'tape_date'
comments column: 'comments'
}
}
public def getName(){
def cdisc = Cdisc.findById(this.id)
return cdisc.name
}
}
TapeController.groovy
def list = {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
[tapeInstanceList: tape.findAllByCommentsLike('%Test%'), tapeInstanceTotal: Tape.count()]
}
Finally displaying name from table cdisc using the getter
list.gsp
<g:each in="${tapeInstanceList}" status="i"
var="tapeInstance">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td><g:link action="edit" id="${tapeInstance.id}">
${fieldValue(bean: tapeInstance, field: "id")}
</g:link></td>
<td>
${fieldValue(bean: tapeInstance, field: "tapeDate")}
</td>
<td>
${fieldValue(bean: tapeInstance, field: "comments")}
</td>
<td>${tapeInstance.getName()}</td>
</g:each>
Thus we are using a getter to get the data from the 2nd table in another database.
Worked for me. Let me know if theres any other workaround.
Related
I am trying to display two tables in my ASP.NET MVC view from a stored procedure which returns 2 tables. When I tried to access the stored procedure result, I was able to retrieve only the first result set and not the second one.
In the stored procedure result, both the tables are obtained by querying multiple tables in the database. Stored procedure is saved as testsp
CREATE PROCEDURE [testsp]
AS
BEGIN
SELECT TOP 20 CONCAT(col1,' : ', col2) AS 'cols'
FROM table1
WHERE CreatedBy IN (SELECT col11 FROM table2
WHERE col12 = 456 AND Curr = 1)
ORDER BY CreatedAt DESC
SELECT TOP 20 CONCAT(col1,' : ', col2) AS 'cols'
FROM table1
WHERE CreatedBy = (SELECT col1 FROM table2 WHERE col12 = 123)
ORDER BY CreatedAt DESC
END
After creating the stored procedure, I included the stored procedure in the model and tried to access it in the controller using the following code:
public class TestController : Controller
{
public ActionResult Index()
{
DBEntities r = new DBEntities();
var data = r.testsp().ToList();
ViewBag.tests = data;
return View();
}
}
In the view, I tried to display it using the following code:
<table id="data" class="table table-bordered table-striped table-responsive">
<tbody>
#foreach (var item in ViewBag.tests)
{
<tr>
<td>
#item
</td>
</tr>
}
</tbody>
</table>
This displayed the first table and not the second one.
How do I access both tables from the stored procedure result, in the controller and display them in the view?
SP cannot have simply two selects. SP would exit after the first select command execution.
Three Choices:
Use Union to combine both the selects.
Define REFCUR and return the cursor from SP
For a more advanced solution develop UDT(User Defined Types).
I use html encoding for my form input fields. I have a form to create a new user object, where one can insert a name for the new user. To prevent this input field from script injection I do encodeAsHTML() in the save() action listed below.
The problem:
1. the entered name is: Schäfchen
2. this would be validated correctly after my validation rules below
3. html encoding transform ä into \auml which will fail the validation
How can I achieve that the name which in html encoded will be correctly validated?
Given the following Grails class:
class User {
String name
static constraints = {
name blank: false, validator: { val, obj ->
Pattern pattern = Pattern.compile("[a-zA-Z0-9äöüßÄÖÜ\\- ]+")
pattern.matcher(val).matches()
}
}
}
in my UserController.groovy:
dev save() {
def name = params?.name?.encodeAsHTML()
def user = new User()
user.name = name
user.save()
}
You should use encodeAsHTML() only in your GSP views.
See: http://grails.org/doc/latest/ref/Tags/each.html
<tbody>
<g:each status="i" in="${itemList}" var="item">
<!-- Alternate CSS classes for the rows. -->
<tr class="${ (i % 2) == 0 ? 'a' : 'b'}">
<td>${item.id?.encodeAsHTML()}</td>
<td>${item.parentId?.encodeAsHTML()}</td>
<td>${item.type?.encodeAsHTML()}</td>
<td>${item.status?.encodeAsHTML()}</td>
</tr>
</g:each>
</tbody>
I am new to struts. I dont know exactly if my solution for my problem is correct or not.
My problem is I have two tables as shown below
I would like to create an HTML table based on the above tables, showing the fields, name of group, id of group, and name of sub group and Id of subgroup. I tried to use list and iterator. But am not able to get both the values(both name and id)
inside class
public List getName() {
return namesHead;
}
public void setName(List name) {
this.namesHead = name;
}
public String listModules() {
SessionFactory factory = HibernateLoginUtil.getFactory();
Session session = factory.openSession();
Query q1 = session.createQuery ("select id,name FROM TableUsrModuleGroup WHERE stat='active'");
for(Iterator it = q1.iterate() ; it.hasNext() ;) {
Object row[] = (Object[]) it.next();
namesHead.add (row[1]); //put the name
}
return SUCCESS;
}
in JSP page
<table>
<s:iterator status="status" value="namesHead" >
<tr><td><s:property/></td></tr>
</s:iterator>
</table>
(only name of group can i get from the above code, I need to display group name, group Id, and name of sub group and Id of sub group)
If you are using Hibernate, I think that the simplest option is to map the two classes and then recover both with a HQL query. For instance:
public class Group {
#OneToMany (mappedBy = "group", fetch = FetchType.LAZY)
private Collection <SubGroup> subgroup;
... // Rest of the class, getters and setters
}
public class SubGroup {
#ManyToOne (fetch = FetchType.LAZY)
private Group group;
... // Rest of the class, getters and setters
}
Then you have to make this HQL query to get the Group class:
Query q = session.createQuery ("FROM SubGroup");
List<SubGroup> subgroups = (List<SubGroup>) q.list();
Then you set an attribute with the subgroups in the Action and then you access to them in the jsp.
<table>
<s:iterator value="subgroups" >
<tr>
<td>
<s:property value="name"/>
</td>
<td>
<s:property value="id"/>
</td>
<td>
<s:property value="group.name"/>
</td>
<td>
<s:property value="group.id"/>
</td>
</tr>
</s:iterator>
</table>
I hope it helps =)
Fetch object, not specific fields from database. You must have getter and setters for that object in your action, then in JSP you can get all properties of that object (don't forget setters/getters for object).
I am a newbie in Groovy and grails. I want to display the current project of an employee in employee List. I can only get the current project of an employee by going to ProjectMember class. My idea is that I get the current project of every employee and then put it in a list which I then iterate over in the .gsp.
class EmployeeController {
def list = {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
def currentProject = [ProjectMember];
List<Employee> employeeList = Employee.list(params)
System.out.print("PREV SIZE" + currentProject.size())
for(Employee emp: employeeList) {
def current = ProjectMember.findAllByEmployeeAndEndDateIsNull(emp, [sort: "project.name", order: "asc"])
System.out.print(current.project.name);
// This is working, I can get the current projects of the employee
if(!current.empty) {
currentProject.add(current);
// Here is the code I didn't understand I really don't know
// if the project is added in the list.
// Everytime I try to display the contents of the list using foreach,
// I always get an error. MissingProperty
}
}
[currentProject: currentProject,
employeeInstanceList: Employee.list(params),
employeeInstanceTotal: Employee.count()]
}
}
class ProjectMember {
Employee employee
EmployeeRole role
Date startDate
Date endDate
String notes
static belongsTo = [project: Project]
}
class Project {
String name
String alternateName
boolean useAlternateNameInResume = false
String summary
String duration
String skills
String technologies
Date startDate
Date endDate
static hasMany = [members: ProjectMember]
}
And lastly the view, list.gsp:
<g:each in="${employeeInstanceList}" status="i" var="employeeInstance">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'} clickable" onclick="window.location='<g:createLink action='show' id='${employeeInstance.id}' />'">
<td>${employeeInstance.idNo?.encodeAsHTML()}</td>
<td>${fieldValue(bean: employeeInstance, field: "fullNameWithMiddleName")}</td>
<td>${employeeInstance.position}</td>
<td>
<g:each in="${currentProject}" var="currentProject" status ="j">
${fieldValue(bean: currentProject, field: "project.name")}
</g:each>
<g:if test="${currentProject.empty}">
No projects yet
</g:if>
</td>
</tr>
</g:each>
Everything works fine except for the current project which doesn't display anything.
Try
<g:each in="${currentProject}" var="project">
${fieldValue(bean: project, field: "name")}
</g:each>
Let's say, i have this scenerio:
But let's say i have hundreds of those checkBoxes, which i need to handle everything at same time after submiting a form. I then will need to save to the BD something based on which boxes are checked, and the id of each block
So, i need this:
a) a way to know which checkboxes are checked, within hundreds of them
b) each checkbox should be 'linked' with an id which im gona pass, so that a specific action will be performed.
I have a <g:each> tag writing me the whole table, reading values from the DB. I would appreciate any help with this,
Thanks in advanced, RR
You can bind the params to a List property of a domain object or command object.
View:
<g:each in="${elements}">
<g:checkBox name="elementSelected[${it.id}]" value="${it.id}" />
</g:each>
Command Object:
class ElementCommand {
List elementSelected
}
Controller:
def execute = { ElementCommand cmd ->
cmd.elementSelected.each {
if (it) {
processId(it.toInteger())
}
}
}
In your gsp you need to display all the checkboxes:
<g:each in="${model}" status="i" var="invoiceItem">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td>
<g:checkBox name="invoiceItem_${i}"/>
</td>
</tr>
</g:each>
In the controller action you need to map the selected checkboxes to your domain objects
List invoiceList = session.invoiceList
params.each {
if (it.key.contains("invoiceItem_")){
if (it.value.contains("on")){
InvoiceItem invoiceItem = invoiceList.get((it.key - "invoiceItem_") as Integer)
}
}
}