I am learning Eclipse Scout... I have connected to Sql server, fetching data using Object[][]...now, I want to fetch data using beans, beanarray holder...
I dont know the process...
I have created bean Users!
I have populated bean using service, using this example: http://www.eclipse.org/forums/index.php/t/310526/
So can someone explain how to use beans in scout, to populate table, or form...
Make a bean example: users
Fill the bean in service example: get user data from users table
populate table using that bean...
tnx
Java POJO (bean)
If you are working with plain old java object (POJO) like this:
public class User {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
You can populate an array of those POJO like this:
public User[] loadAll() throws ProcessingException {
BeanArrayHolder<User> beansArray = new BeanArrayHolder<User>(User.class);
SQL.selectInto(" select first_name, last_name " +
" from users " +
" into :{FirstName}, :{LastName} ", beansArray);
return beansArray.getBeans();
}
To populate your table, you need to do it by hand. For example on the client side:
for (User user : beansArray.getBeans()) {
ITableRow row = getTable().createRow();
getTable().getNameColumn().setValue(row, user.getLastName());
getTable().getFirstNameColumn().setValue(row, user.getFirstName());
getTable().addRow(row, true);
}
A mapping server side is also possible. But in this case, you should definitively consider to use table data (see the next section)
Table data
You should ensure that you are using bean based TableData. Read this answer to know how you can differentiate table based TableData and bean based TableData.
Assuming you have a UserTableField like this in your Form:
#Order(10.0)
#FormData(sdkCommand = FormData.SdkCommand.USE, value = AbstractTableFieldBeanData.class, defaultSubtypeSdkCommand = FormData.DefaultSubtypeSdkCommand.CREATE)
public class UserTableField extends AbstractTableField<UserTableField.Table> {
#Order(10.0)
public class Table extends AbstractExtensibleTable {
public LastNameColumn getLastNameColumn() {
return getColumnSet().getColumnByClass(LastNameColumn.class);
}
public FirstNameColumn getFirstNameColumn() {
return getColumnSet().getColumnByClass(FirstNameColumn.class);
}
#Order(10.0)
public class FirstNameColumn extends AbstractStringColumn {
#Override
protected String getConfiguredHeaderText() {
return TEXTS.get("FirstName");
}
}
#Order(20.0)
public class LastNameColumn extends AbstractStringColumn {
#Override
protected String getConfiguredHeaderText() {
return TEXTS.get("LastName");
}
}
}
}
You should be able to do something like that in your service:
UserTableRowData rowData = formData.getUserTable().addRow();
rowData.setFirstName("John");
rowData.setLastName("Smith");
Instead of adding the rows manualy, if you want to have a SQL query to populate the table, you can do something like that:
BeanArrayHolder<User> beansArray = new BeanArrayHolder<User>(User.class);
SQL.selectInto(" select first_name, last_name " +
" from users " +
" into :{UserTable.FirstName}, :{UserTable.LastName} ", formData);
It works the same way for TablePageData, see an example in our tutorial:
MiniCrm Tutorial > Write the first page > Load data on the server
Related
There are 100k+ records. I want to convert my column1, column2 in a HashMap. Later sending .toString() in a robust way.
Desired result is a string: [col1=val1 ,col2=val2,......]
Is there is a way to directly convert it into String?
String queryString="SELECT distinct c.billing_account_no,concat(p.eligibility_id, c.seq_id) AS full_name FROM Siebel_promo_prod_offer_fed p , ppm_offerability_account_info c WHERE p.corp_code='"+corpCode+"' and p.ELIGIBILITY_ID='"+ruleId+"'"; //System.out.println(queryString);
List<List<Object>> accountIDs= session.createSQLQuery(queryString).setResultTransformer(Transformers.TO_LIST).list(); //System.out.println("After query....");
for(List<Object> x: accountIDs){
map.put((String)x.get(0),(String)x.get(1));
}
I am using Java 7 technology.
I would recommend to you change your ResultTransformer to Transformers.aliasToBean(MyDto.class):
String queryString = "SELECT distinct c.billing_account_no AS billingAccount, concat(p.eligibility_id, c.seq_id) AS fullName FROM Siebel_promo_prod_offer_fed p , ppm_offerability_account_info c WHERE p.corp_code = :corpCode and p.ELIGIBILITY_ID = :ruleId;
List<MyDto> accountIDs = session.createSQLQuery(queryString)
.setString("corpCode", corpCode) // correct way to add params
.setString("ruleI", ruleId) // correct way to add params
.setResultTransformer(Transformers.aliasToBean(MyDto.class))
.list();
for(MyDto myDto: accountIDs){
map.put(myDto.getBillingAccount(), dto.getFullName());
}
Transformers.aliasToBean will transform your query rows into a POJO. Notice the name of the result column('AS billingAccount', 'AS fullName') name and the class attributes ('billingAccount', 'fullName'), they have the same name.
class MyDto {
private String billingAccount;
private String fullName;
public MyDto() {
}
public String getBillingAccount() {
return billingAccount;
}
public void setBillingAccount(String billingAccount) {
this.billingAccount = billingAccount;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#Override
public String toString() {
return billingAccount + "=" + fullName;
}
}
calling accountIDs.toString(); you will have the desired string. You Already have the simplest way to transform List to Map.
NOTE: DO NOT USE CONCATENATION IN YOUR QUERIES, SQL INJECTIONS CAN BE EXECUTED.
PD: why not return the accountIDs?
I have a Book class:
public class Book extends SugarRecord {
private String mBookName;
private String mAuthorName;
private List<Page> mPageList;
public Book() {
}
public Book(String bookname, String authorName) {
mBookName = bookname;
mAuthorName = authorName;
mPageList = new ArrayList<>();
}
public String getAuthorName() {
return mAuthorName;
}
public void setAuthorName(String authorName) {
mAuthorName = authorName;
}
public String getBookName() {
return mBookName;
}
public void setBookName(String bookName) {
mBookName = bookName;
}
public void addPage(Page page) {
mPageList.add(page);
}
}
and the Page class:
public class Page extends SugarRecord {
private String mText;
public Page() {
}
public Page(String text) {
mText = text;
}
public String getText() {
return mText;
}
public void setText(String text) {
mText = text;
}
}
I am testing it with this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Book book = new Book("Some Book Title", "John Doe");
Page page1 = new Page("Once upon a time there was a very lonely bunny who wanted some friends.");
Page page2 = new Page("So he found some friends, and everyone was happy.");
Page page3 = new Page("The end!");
book.addPage(page1);
book.addPage(page2);
book.addPage(page3);
book.save();
}
}
However it is not working as expected. It is trying to make mPageList its own column with this .schema:
CREATE TABLE BOOK ( ID INTEGER PRIMARY KEY AUTOINCREMENT , M_AUTHOR_NAME TEXT, M_BOOK_NAME TEXT, M_PAGE_LIST );
What I'd really like it to do is not treat the list as its own column but instead save the Pages to the PAGE table, with additional ids that reference this Book class (so what I am expecting is something like ID, BOOK_ID, M_TEXT). In short, persistence operations that cascade through nested child objects.
Can this be done in SugarORM?
No ORM database(SugarORm, DBFLow etc) supports List column. As you know sql don't have this datatype as well.
That's the reason why you are getting this error. If you ask me how you are saving list to ORM. I use Gson.
Declare Pagelist as string.
String Pagelist;
Before saving it to database convert it to Json string with the help Gson library.
Gson gson = new Gson();
String value = gson.toJson(your_page_list);
when retrieving from database convert the json string to List using Gson.
List<Page> page_list;
Type typeIndicatorForGson = new TypeToken<ArrayList<Page>>() {}.getType();
Gson myGson = new Gson();
page_list = myGson.fromJson(page_json_data_from_database, typeIndicatorForGson);
No List<Object> available on SugarORM. The way you can manage this is a little tricky. In few words, you can manage 1 to N relations, upside down. Take a look to the next example
Lets suppose a Team object which can have N Person objects. Normally you will use a List<Person> in your class Team in this way:
public class Team {
String teamName;
List<Person>
...
}
public class Person {
String name;
String rol;
...
}
Well, it is not possible on SugarORM. But you can add Team as a property in Person, so, any Person's instance should contain a reference to the Team object it belong.
public class Team extends SugarRecord<Team> {
String teamName;
...
}
public class Person extends SugarRecord<Person> {
String name;
String rol;
Team team;
...
}
Then you can get all the Person objects from Team with a method (in the Team class) like:
public class Team extends SugarRecord<Team> {
String teamName;
...
public List<Person> getPersons(){
return Person.find(Person.class, "id = ?", String.valueOf(this.getId()));
}
}
So, you can manage 1 to N relations, but you can't manage N to M relationships (Person belonging to more than one Team object).
IMO the way to manage this is using an Associative Entity in order to split N to M into two 1 to N relationships.
As you can see SugarORM is not allowing you to think just in terms of objects, but, any case you can save a lot of boiler plate coding.
I have created a Bean Class using Builder Pattern and having issues creating an object from a yaml file.
Here is a sample class (Actual class is quite big, this is just an excerpt incase if you wanted to answer with an example):
public class ClientBuilder {
private final String firstName;
private final String lastName;
private final String displayName;
private ClientBuilder(Builder builder) {
firstName = builder.firstName;
lastName = builder.lastName;
displayName = builder.displayName;
}
public static class Builder {
private final String displayName; // Mandatory Attribute
public Builder( String displayName ) {
this.displayName = displayName;
}
private String firstName;
private String lastName;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public ClientBuilder build() {
return new ClientBuilder(this);
}
}
#Override
public String toString() {
StringBuffer sbf = new StringBuffer();
sbf.append("New Company Object: \n");
sbf.append("firstName : " + this.firstName + "\n");
sbf.append("lastName : " + this.lastName + "\n");
sbf.append("displayName : " + this.displayName + "\n");
return sbf.toString();
}
}
I am using snakeyaml to load the file but any yaml api would work. Since the displayName is a mandatory param, I want to pass that value while creating the instance. The other params can be passed while creating the object but I would like the option to load them through yaml file.
I am able to load the yaml file if I use java bean. Is there a way to instantiate builder objects?
I tried:
InputStream input = new FileInputStream(new File("src/main/resources/client.yaml"));
Yaml yaml = new Yaml();
Builder builder = new Builder("Display Name");
builder = (Builder) yaml.loadAs(input, ClientBuilder.Builder.class);
ClientBuilder client = builder.build();
System.out.println(client.toString());
but I get following error:
Exception in thread "main" Can't construct a java object for tag:yaml.org,2002:com.xxx.xxx.xxx.ClientBuilder$Builder; exception=java.lang.NoSuchMethodException: com.xxx.xxx.xxx.ClientBuilder$Builder.<init>()
in 'reader', line 2, column 1:
firstName: "Jaypal"
SnakeYaml is a very powerful library & it provides support for creating instance based on constructor injection.
/**
* create JavaBean
*/
public void testGetBeanAssumeClass() {
String data = "--- !!org.yaml.snakeyaml.constructor.Person\nfirstName: Andrey\nage: 99";
Object obj = construct(data);
assertNotNull(obj);
assertTrue("Unexpected: " + obj.getClass().toString(), obj instanceof Person);
Person person = (Person) obj;
assertEquals("Andrey", person.getFirstName());
assertNull(person.getLastName());
assertEquals(99, person.getAge().intValue());
}
/**
* create instance using constructor arguments
*/
public void testGetConstructorBean() {
String data = "--- !!org.yaml.snakeyaml.constructor.Person [ Andrey, Somov, 99 ]";
Object obj = construct(data);
assertNotNull(obj);
assertTrue(obj.getClass().toString(), obj instanceof Person);
Person person = (Person) obj;
assertEquals("Andrey", person.getFirstName());
assertEquals("Somov", person.getLastName());
assertEquals(99, person.getAge().intValue());
}
Junit code sample can be viewed here.
So your code still holds good. You may need to change yaml content with proper format. Once done, you are all set.
The exception is about there not being a no-arg constructor in Builder, as you probably figured out.
What you could do is to allow no-arg constructor for Builder and add corresponding setter and getter for displayName to it. Then simply throw an exception in build() if displayName is not set (or provide a default value for it). The exception can be a runtime one, or you could make it clear and add an explicit throws.
While it is not the prettiest solution, it should work just fine. The fact that the Builder is created without a mandatory argument should not matter, as it is the ClientBuilder that needs to be constructed properly (as the factory/builder is used to ensure that each instance of whatever it is building is correct).
I have no way to access any yaml parsing tools for Java currently, but if there is any way I could improve my answer, let me know - I will be happy to do so.
Any idea on how to define indexes on data stored with Akiban's Persistit key/value store?
There isn't first class/API support for secondary indexes in Persistit. That isn't to say you can't create indexes though!
What is an index? In practice, all an index contains is another copy of the data. For example, in a relational database with a users table, an index on the first_name column would allow efficient look-up by first name. That can be achieved by storing an additional copy of the first name with the primary identifier to create a "link" back to the main row.
Here's an isolated example of that:
import com.persistit.*;
import com.persistit.exception.*;
import java.io.*;
import java.util.*;
public class IndexDemo implements AutoCloseable
{
public static class User implements Serializable
{
public int id;
public String firstName;
public String lastName;
public User() {
}
public User(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format("User(%d, %s, %s)", id, firstName, lastName);
}
}
private final Persistit db;
public IndexDemo() throws PersistitException {
Configuration c = new Configuration();
c.getBufferPoolMap().get(16384).setCount(32);
c.getVolumeList().add(new VolumeSpecification(
"IndexDemo.vol,create,pageSize:16384,initialPages:5,extensionPages:5,maximumPages:100"
));
this.db = new Persistit(c);
}
#Override
public void close() throws PersistitException {
db.close();
}
public Exchange userEx() throws PersistitException {
return db.getExchange("IndexDemo", "users", true);
}
public Exchange firstNamesEx() throws PersistitException {
return db.getExchange("IndexDemo", "firstNames", true);
}
// Save the user, both primary and secondary firstName index
public void saveUser(User u) throws PersistitException {
Exchange ex = userEx();
// Primary entries: key of ID and value of full User
ex.getKey().append(u.id);
ex.getValue().put(u);
ex.store();
// First name index: key of (name,ID)
ex = firstNamesEx();
ex.append(u.firstName).append(u.id);
ex.store();
}
// Look-up the user by ID
public User userByID(int id) throws PersistitException {
Exchange ex = userEx();
// Construct and fetch our key
ex.getKey().append(id);
ex.fetch();
// Careful: may not exist
if(!ex.getValue().isDefined()) {
return null;
}
// Otherwise get it from the value
return (User)ex.getValue().get();
}
// Index scan for users with firstName, look-up and return all matches
public List<User> usersByFirstName(String firstName) throws PersistitException {
List<User> users = new ArrayList<>();
Exchange ex = firstNamesEx();
// Iterate over only entires matching firstName
ex.append(firstName).append(Key.BEFORE);
while(ex.next()) {
// Index to second component (id) and decode
int id = ex.getKey().indexTo(1).decodeInt();
// And lookup the user
users.add(userByID(id));
}
return users;
}
public static void main(String[] args) throws PersistitException {
try(final IndexDemo demo = new IndexDemo()) {
System.out.println("No Transaction:");
runDemo(demo);
}
try(final IndexDemo demo = new IndexDemo()) {
System.out.println("Transaction:");
demo.db.getTransaction().run(new TransactionRunnable() {
#Override
public void runTransaction() throws PersistitException {
runDemo(demo);
}
});
}
}
public static void runDemo(IndexDemo demo) throws PersistitException {
demo.saveUser(new User(1, "John", "Doe"));
demo.saveUser(new User(2, "John", "Smith"));
demo.saveUser(new User(3, "Sally", "Jones"));
System.out.println(" User 1: " + demo.userByID(1));
System.out.println(" User 10: " + demo.userByID(10));
System.out.println(" Users named John:");
for(User u : demo.usersByFirstName("John")) {
System.out.println(" " + u);
}
}
}
Running yields this output:
No Transaction:
User 1: User(1, John, Doe)
User 10: null
Users named John:
User(1, John, Doe)
User(2, John, Smith)
Transaction:
User 1: User(1, John, Doe)
User 10: null
Users named John:
User(1, John, Doe)
User(2, John, Smith)
There isn't too much going on:
User POJO with a few attributes
Basic Persistit configuration and start-up
Helpers for saving, look-up by primary/ID and scan by first name
Demo usage of all the helpers
Main runs the demo both inside and outside of a transaction
All the pieces are there for building something extremely simple, like this demo, to something very sophisticated, like a complete SQL server.
I have created json in javascript and I am putting this json in one array. I have stored the array in a database field named "exp_values" like :
[{"concentration":"5","answers":10},{"concentration":"5","answers":20},{"concentration":"5","answers":78}]
I want to retrieve from the database. I am using spring and I created pojo(bean) class like
public class ExperimentParameterBean {
private String username;
private String[] exp_values;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String[] getExp_values() {
return exp_values;
}
public void setExp_values(String[] arrayData) {
this.exp_values = arrayData;
}
}
I used hibernate for retrieving values from the database. I want this array as it is
in java. How can I do this? I have knowledge of spring and hibernate. I want to only get this array from the database in the JSONObject fromat.
my problem solved. i am storing json as text datatype in mysql