Fed Reserve Bank (San Francisco ) Ask: Is It Still Worth Going to College?

In today’s Federal Reserve Bank (San Francisco) Economic Letter, the value of a 4 years university/college degree is questioned, and findings are rather shocking : it will take 15 to 20 years in order to return the investment on average.

Table 1 Maximum tuitions by breakeven age and discount rates

Maximum tuitions by breakeven age and discount rates

The article concluded:

Earning a four-year college degree remains a worthwhile investment for the average student. Data from U.S. workers show that the benefits of college in terms of higher earnings far outweigh the costs of a degree, measured as tuition plus wages lost while attending school. The average college graduate paying annual tuition of about $20,000 can recoup the costs of schooling by age 40. After that, the difference between earnings continues such that the average college graduate earns over $800,000 more than the average high school graduate by retirement age.

Although there are stories of people who skipped college and achieved financial success, for most Americans the path to higher future earnings involves a four-year college degree. We show that the value of a college degree remains high, and the average college graduate can recover the costs of attending in less than 20 years. Once the investment is paid for, it continues to pay dividends through the rest of the worker’s life, leaving college graduates with substantially higher lifetime earnings than their peers with a high school degree. These findings suggest that redoubling the efforts to make college more accessible would be time and money well spent.

Good Article: 30 Financial Milestones You Need To Hit By Age 30

This article was published on moneyaftergraduation.com by Bridget, and I keep a copy here.

30 Financial Milestones You Should Meet Before Age 30

1. Financially independent of your parents. Parents always want to help but eventually their doting will become a hinderance when it comes to establishing yourself as a self-sufficient adult. I’m a firm advocate that you should establish complete financial independence of your parents in your early twenties, but if an unexpected emergency or crippling debt threw you back in the nest for a few years, make sure you claw your way out by 30.
2. Debt free. There’s no excuses to carry the spending mistakes of your youth into your 30′s, so your consumer debt should be long gone. Depending on what and how long you studied in university, your student loans should also be vanquished by age 30.
3. Out of overdraft. Sometimes your chequing account runs dry when you’re trying to make ends meet, but by age 30 you’ve had a bank account long enough to know how to stay out of the red. If overdraft is a habit for you, it’s one you need to break by 30.
4. Established good credit history. Maybe you missed some payments and even had a debt go to collections when you were young and foolish, but by 30 you should have redeemed yourself from these mistakes. A solid credit history will help you with big purchases like a home, but also shows you pay your bills on time and don’t live at the limit of your cards.
5. Have $25,000+ saved for retirement. If that number made your eyes bulge out, you better get saving. As a general rule, I think you should aim to have one-year’s worth of your salary banked for retirement by age 30, but if your spent a long time in university or had a slow start to your career, this may not be possible. $25,000 is a good amount to aim for if you need to set a target. Even if you don’t start saving until age 25, you’ll only need to put $5,000/yr away to meet this goal.
6. Started an investment portfolio. Whether it’s something simple like mutual funds or more advanced like common stocks, by age 30 you have to have your money diversified in something beyond a basic savings account.
7. Established an emergency fund. There are mixed opinions about just how much you should have set aside in case trouble comes your way, but the general rule is enough to cover 3-6 months of essential expenses.
8. Properly insured. Part of being a responsible adult is protecting yourself, and that includes small things like tenant insurance for your apartment right up to disability insurance. If you don’t have coverage through an employer, you should also look for health/dental insurance to manage those costs.
9. Maximizing employer benefits. If you’re lucky enough to work somewhere that provides you with perks, you should know what they are and be using them — it’s free money! Make sure you opt in to things like employer retirement plans and utilize spending accounts for learning & development. Don’t let these things go to waste!
10. In the habit of tracking your spending. It’s a tedious chore but the only way you’re ever going to manage your money is if you know where it’s going. By 30 you should be in the habit of tracking purchases and making sure you’re spending less than you earn.
11. Done with impulse purchases. The sooner you give up the habit of shopping when bored or grabbing goodies while you wait in the grocery store checkout, the better. Going into your 30′s, you understand your money can only work for you when you have it, so you’ve gotta stop spending it on things you didn’t originally want or need.
12. Willing to spend where it counts. As you near 30, your dorm-room living days are probably long over and you’re ready to invest in some nice furniture or pots and pans that aren’t coming second-secondhand (thirdhand?). Whether its your wardrobe, your home, or even items like a gym membership, you understand that sometimes quality costs and you’re willing to spend where it matters.
13. In the habit of regularly checking your credit report. You can do this once a year and for FREE, and it’s one of the simplest ways to protect yourself against identity theft while maintaining good financial health. You have no excuses not to!
14. On top or ahead of all your monthly bills. In your disorganized youth, you probably forgot to pay a bill or missed a deadline, but by 30 you should be well into the habit of meeting all your deadlines. Set up an auto-pay from your chequing account to ensure you never miss a due date!
15. At least one big splurge you saved up for and paid in full with cash. Whether it’s an extensive backpacking adventure or a new car, you should have at least one “fun” financial triumph behind you by the time you hit 30. Save up and spend! You have to enjoy your money as you take care of it!
16. An understanding of personal income taxes and how to minimize what you pay. Understanding what tax bracket you fall into and what credits are available to you means more money in your pocket every year. Make sure you’re contributing to your RRSP and claiming all other available deductions in a way that ensures you pay the least amount of taxes possible!
17. Diligently saving for a big purchase. Whether it’s a wedding or a down-payment on your home, there might be something very expensive coming up that takes a few years of planning. By 30 you should not only have a plan, but actively making headway towards your goal.
18. A clear direction of your career. Your job is your major financial asset, and the one that generates the most income for you. By 30, not only should you know what industry you work in, you should have logged a few years of professional experience in your field. If you were in school pursuing a graduate or professional degree, this might not be many years, but the most important thing is that you’ve started establishing yourself to reap the rewards of hard work in your 30′s and 40′s.
19. A profitable side income. However small, having a second (or third, or fourth) revenue stream is important. This can be a small part-time endeavour or something as simple as dividend payments from stocks you own. In any case, you should have an alternative source of income beyond your main employment.
20. A positive, growing net worth. By 30, it should be true that your assets – liabilities = positive number. This might be a challenge depending on how much debt you took on for school or how foolish you were in your early 20′s, but ultimately your net worth should be growing at a quick clip as you enter your 30′s. I suggest increasing your net worth by at least $25,000 per year.
21. A BHAG for your finances. BHAG stands for “Big Hairy Audacious Goal”. This can be something like retiring with $2 million or purchasing a vacation property by age 40 or earning a salary of $100,000 per year. Whatever it is you want, make sure it’s BIG and challenging so you can work towards it a little bit every year. When you meet your goal, make another.
22. An understanding and a plan of how your money will deliver the lifestyle you want. Following point #21, to their credit millennials dream big — sometimes a little TOO big! If you’re planning to pay off all your debts, get married, buy a home, have a child, get a promotion, buy a new car, and save $50,000 for retirement by age 30, you might need a reality check. Take a critical and realistic look at your stupid goals and determine if they really are feasible. Maybe make adjustments by lowering the target or extending the deadline. Remember, you’re not in a race! You will still be working and saving money at 31, so go ahead and delay some things until they’re really financially feasible.
23. So over measuring your finances against that of your friends. By age 30, some of your peers will have enjoyed tremendous success in their careers, and others will be struggling. At 21 there was little predict who would end up where, but by now the cards have been dealt and maybe you didn’t end up a millionaire by 25. While it can be hard to quell jealousy when someone is enjoying more financial success than you, your situation is yours and you have to manage it best you can. It’s time to get over this, bury the green-eyed monster, and move on. (This also goes for feeling superior to friends who are not managing their finances as well as you. Be an example, not an arrogant ass).
24. Less consumption-oriented. It’s easy to be dazzled by bright & shiny things in your 20′s, but heading into your thirties you understand that a new car or a big home are just things and ultimately don’t matter — and certainly are no testament to your financial health or success! By age 30 you should no longer be using material things to measure progress.
25. A healthy relationship with credit cards. By age 30 you should only be using credit cards for the conveniences and reward perks. You should always pay the bill in full and never miss a due date. You understand that creditors want to make money off of you, not provide you with benefits, so you pursue all rewards cards with caution.
26. A regular contribution to charity. Whether you drop $10-$20 monthly or a few hundred dollars a year to one or many charities, giving is an integral part of personal finance. Find a cause you believe in and do your part to help it succeed. This necessitates not only budgeting, but also serves as a reminder that many are not as fortunate as you and we have a moral obligation to help our communities by sharing our wealth.
27. If you’re part of a couple, a healthy way of sharing money with your partner. Whether it’s splitting bills 50/50 or one paying certain bills and the other person paying the rest, by your 30′s you should have figured out a system that works for both of you. Disagreements about finances are a leading cause of divorce, so getting over this early ensures a healthy wallet and a happy relationship.
28. A commitment to putting free or cheap before convenient. Whether it’s brewing coffee at home or looking for furniture secondhand, it will always be easier to buy new, but it’s in the best interest of your wallet (and the environment!) to seek out alternative ways to get what you want or need without spending much or anything at all. Make use of sites like eBay, Craigslist, and Kijiji or develop your own resources (ie. clothing swaps) and check out used bookstores, consignment shops, and thrift stores.
29. Done paying unnecessary fees. In your 20′s it seems insignificant to withdraw cash from an ATM that is not from your bank and it’s a hassle to call your cable or cellphone provider for a cheaper plan, but if you do these things and are strapped for cash, it’s completely your fault. It may have been forgivable to be careless in your 20′s, but going forward you never want to be paying more than you have to!
30. An understanding and appreciation for the reality that money is only a tool of exchange, and not worth obsessing over. It’s cool to be financially savvy, but don’t let it take over your life. By getting your ducks in a row in you’re 20′s, you’ll be all set to enjoy the financial fruits of your labor in your 30′s and beyond.

CRUD Operations using JPA

I will show how to perform four basic functions, create, read, update and delete (CRUD) on relational database application by using JPA in this post.

I only include two programs in the following. Full source codes can be cloned from https://github.com/henry416/jpatest.
1) Student.java: to define a new entity class;
2) StudentTest.java: to perform CRUD operations;

1. Entity Class: Student.java

package henry416.domain;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Student {
	@Id
	private int id;

	private String name;
	
	private double gpa;
	
	public Student() {}

	public Student(int id) {
		this.id = id;
	}
	
	public Student(int id, String name, double gpa) {
		this.id = id;
		this.name = name;
		this.gpa = gpa;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public double getGpa() {
		return gpa;
	}
	
	public void setGpa(double gpa) {
		this.gpa = gpa;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", gpa="
				+ gpa + "]";
	}

}

2. CRUD Operations: StudentTest.java

package henry416.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import henry416.domain.Student;

public class StudentTest {

	private EntityManager manager;

	public StudentTest(EntityManager manager) {
		this.manager = manager;
	}
 
	public static void main(String[] args) {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
		EntityManager manager = factory.createEntityManager();
		StudentTest test = new StudentTest(manager);

		EntityTransaction tx = manager.getTransaction();
		System.out.println("1. create student records");
		tx.begin();
		try {
			test.createStudents();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();

		System.out.println("2. read student records");
		test.readStudents();

		System.out.println("3. update a student record");
		tx.begin();
		try {
			test.updateStudent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();		

		System.out.println("4. delete a student record");
		tx.begin();
		try {
			test.deleteStudent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();		
		
		System.out.println("5. delete all student records");
		tx.begin();
		try {
			test.deleteStudents();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();		
		
		System.out.println("=> done");
	}

	private void createStudents() {
		// insert a few records
		manager.persist(new Student(1,"Jack Jackson",3.28));
		manager.persist(new Student(2,"Tom Thomson",3.56));
		manager.persist(new Student(3,"Dave Davison",3.65));
		manager.persist(new Student(4,"Neil Nelson",3.56));
		manager.persist(new Student(5,"Mark Markson",3.78));		
	}

	private void readStudents() {
		List<Student> resultList = manager.createQuery("Select s From Student s order by s.id", Student.class).getResultList();
		System.out.println("num of students:" + resultList.size());
		for (Student next : resultList) {
			System.out.println("=> " + next);
		}
	}

	private void updateStudent() {
		// update a student record
		Student stu = manager.find(Student.class, 2);
        	if (stu != null) {
                  System.out.println("from => "+stu);  
        	  stu.setName("Thomas Thomson");
                  stu.setGpa(3.99);
                  System.out.println("to => "+stu);
        	}
	}
	
	private void deleteStudent() {
		// delete ONE record
		Student stu = manager.find(Student.class, 2);
		System.out.println("remove=> "+stu);
		if (stu != null) {
		   manager.remove(stu);
		}

	}
	
	private void deleteStudents() {
		// delete all records
		int deletedCount = manager.createQuery("DELETE FROM Student").executeUpdate();
		System.out.println("total num of records removed => "+deletedCount);
	}
}

3. Result

The following is the execution results:

1. create student records
2. read student records
num of students:5
=> Student [id=1, name=Jack Jackson, gpa=3.28]
=> Student [id=2, name=Tom Thomson, gpa=3.56]
=> Student [id=3, name=Dave Davison, gpa=3.65]
=> Student [id=4, name=Neil Nelson, gpa=3.56]
=> Student [id=5, name=Mark Markson, gpa=3.78]
3. update a student record
from => Student [id=2, name=Tom Thomson, gpa=3.56]
to => Student [id=2, name=Thomas Thomson, gpa=3.99]
4. delete a student record
remove=> Student [id=2, name=Thomas Thomson, gpa=3.99]
5. delete all student records
total num of records removed => 4
=> done

Standalone JPA Project Using Java SE: A Maven Way

In this post, I will show how to create a simple JPA application by using maven and Java SE JDK. All the other libraries will be taken care of by the remote repository in maven, which includes eclipselink and embedded derby db.

I will be focusing on how to use maven to generate, what project structure and programs created, how to execute the application, how to verify the database objects, and what targets can be deployed.

I hope this will help you get started, especially without using any IDEs like Eclipse, Netbean etc.

I won’t go to explain what JPA is. There are many resources and books available.

1. Generate JPA App in Seconds

Make sure to enter ’46’ as artifactID (46 is for com.github.lalyos:standalone-jpa-eclipselink-archetype) when asked in the following:

mvn archetype:generate -DgroupId=henry416 -DartifactId=test1

.................

Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 354: 46
Choose com.github.lalyos:standalone-jpa-eclipselink-archetype version: 
1: 0.0.1
2: 0.0.2
Choose a number: 2: 2
[INFO] Using property: groupId = henry416
[INFO] Using property: artifactId = test1
Define value for property 'version':  1.0-SNAPSHOT: : 
[INFO] Using property: package = henry416
Confirm properties configuration:
groupId: henry416
artifactId: test1
version: 1.0-SNAPSHOT
package: henry416
 Y: : 
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: standalone-jpa-eclipselink-archetype:0.0.2
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: henry416
[INFO] Parameter: artifactId, Value: test1
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: henry416
[INFO] Parameter: packageInPathFormat, Value: henry416
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: henry416
[INFO] Parameter: groupId, Value: henry416
[INFO] Parameter: artifactId, Value: test1
[INFO] project created from Archetype in dir: /home/henry/Test/jpatest/test1
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:42.092s
[INFO] Finished at: Thu Mar 06 21:10:38 EST 2014
[INFO] Final Memory: 10M/25M
[INFO] ------------------------------------------------------------------------

2. Project Structures Generated

henry@brimley:~/Test/jpatest/test1$ ls -ld $(find .)
drwxr-xr-x 3 henry henry 4096 2014-03-06 22:37 .
-rw-r--r-- 1 henry henry   70 2014-03-06 21:10 ./ij.properties
-rw-r--r-- 1 henry henry 1185 2014-03-06 21:10 ./pom.xml
-rwx------ 1 henry henry   60 2014-03-06 21:10 ./run.sh
-rwx------ 1 henry henry  107 2014-03-06 21:10 ./show-derby.sh
drwxr-xr-x 3 henry henry 4096 2014-03-06 21:10 ./src
drwxr-xr-x 4 henry henry 4096 2014-03-06 21:10 ./src/main
drwxr-xr-x 3 henry henry 4096 2014-03-06 21:10 ./src/main/java
drwxr-xr-x 4 henry henry 4096 2014-03-06 21:10 ./src/main/java/henry416
drwxr-xr-x 2 henry henry 4096 2014-03-06 21:10 ./src/main/java/henry416/domain
-rw-r--r-- 1 henry henry  928 2014-03-06 21:10 ./src/main/java/henry416/domain/Department.java
-rw-r--r-- 1 henry henry  992 2014-03-06 21:10 ./src/main/java/henry416/domain/Employee.java
drwxr-xr-x 2 henry henry 4096 2014-03-06 21:10 ./src/main/java/henry416/jpa
-rw-r--r-- 1 henry henry 1597 2014-03-06 21:10 ./src/main/java/henry416/jpa/JpaTest.java
drwxr-xr-x 3 henry henry 4096 2014-03-06 21:10 ./src/main/resources
drwxr-xr-x 2 henry henry 4096 2014-03-06 21:10 ./src/main/resources/META-INF
-rw-r--r-- 1 henry henry 1205 2014-03-06 21:10 ./src/main/resources/META-INF/persistence.xml

The source codes you may be interested in the following separate links:
./pom.xml
./src/main/resources/META-INF/persistence.xml
./src/main/java/henry416/domain/Department.java
./src/main/java/henry416/domain/Employee.java
./src/main/java/henry416/jpa/JpaTest.java

3. Test Run

henry@brimley:~/Test/jpatest/test1$ cat run.sh
mvn compile exec:java -Dexec.mainClass=henry416.jpa.JpaTest

henry@brimley:~/Test/jpatest/test1$ chmod 700 *.sh

henry@brimley:~/Test/jpatest/test1$ ./run.sh 
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building test1 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test1 ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ test1 ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 3 source files to /home/henry/Test/jpatest/test1/target/classes
[INFO] 
[INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) @ test1 >>>
[INFO] 
[INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) @ test1 <<<
[INFO] 
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ test1 ---
num of employess:2
next employee: Employee [id=3, name=Captain Nemo, department=java]
next employee: Employee [id=2, name=Jakab Gipsz, department=java]
.. done
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 27.590s
[INFO] Finished at: Thu Mar 06 21:15:27 EST 2014
[INFO] Final Memory: 24M/61M
[INFO] ------------------------------------------------------------------------

4. Result

henry@brimley:~/Test/jpatest/test1$ cat show-derby.sh 
mvn dependency:copy-dependencies
java -cp 'target/dependency/*' org.apache.derby.tools.ij -p ij.properties

henry@brimley:~/Test/jpatest/test1$ ./show-derby.sh 
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building test1 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.8:copy-dependencies (default-cli) @ test1 ---
[INFO] Copying eclipselink-2.2.1.jar to /home/henry/Test/jpatest/test1/target/dependency/eclipselink-2.2.1.jar
[INFO] Copying derbytools-10.8.2.2.jar to /home/henry/Test/jpatest/test1/target/dependency/derbytools-10.8.2.2.jar
[INFO] Copying derby-10.8.2.2.jar to /home/henry/Test/jpatest/test1/target/dependency/derby-10.8.2.2.jar
[INFO] Copying javax.persistence-2.0.3.jar to /home/henry/Test/jpatest/test1/target/dependency/javax.persistence-2.0.3.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.026s
[INFO] Finished at: Thu Mar 06 21:17:51 EST 2014
[INFO] Final Memory: 8M/21M
[INFO] ------------------------------------------------------------------------
ij version 10.8
CONNECTION0* - 	jdbc:derby:simpleDb
* = current connection
ij> show schemas;
TABLE_SCHEM                   
------------------------------
APP                           
NULLID                        
SQLJ                          
SYS                           
SYSCAT                        
SYSCS_DIAG                    
SYSCS_UTIL                    
SYSFUN                        
SYSIBM                        
SYSPROC                       
SYSSTAT                       
TEST1                         

12 rows selected
ij> select * from TEST1.DEPARTMENT;
ID                  |NAME                
-----------------------------------------
1                   |java                

1 row selected
ij> select * from TEST1.EMPLOYEE;
ID                  |NAME                |DEPARTMENT_ID       
--------------------------------------------------------------
3                   |Captain Nemo        |1                   
2                   |Jakab Gipsz         |1                   

2 rows selected
ij> exit;

5. Deployment Target

henry@brimley:~/Test/jpatest/test1/target$ ls -ld $(find .)
drwxr-xr-x 4 henry henry    4096 2014-03-06 21:17 .
drwxr-xr-x 4 henry henry    4096 2014-03-06 21:15 ./classes
drwxr-xr-x 4 henry henry    4096 2014-03-06 21:15 ./classes/henry416
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:15 ./classes/henry416/domain
-rw-r--r-- 1 henry henry    1691 2014-03-06 21:15 ./classes/henry416/domain/Department.class
-rw-r--r-- 1 henry henry    1888 2014-03-06 21:15 ./classes/henry416/domain/Employee.class
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:15 ./classes/henry416/jpa
-rw-r--r-- 1 henry henry    3080 2014-03-06 21:15 ./classes/henry416/jpa/JpaTest.class
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:15 ./classes/META-INF
-rw-r--r-- 1 henry henry    1205 2014-03-06 21:15 ./classes/META-INF/persistence.xml
drwxr-xr-x 2 henry henry    4096 2014-03-06 21:17 ./dependency
-rw-r--r-- 1 henry henry 2671577 2014-03-06 21:17 ./dependency/derby-10.8.2.2.jar
-rw-r--r-- 1 henry henry  174969 2014-03-06 21:17 ./dependency/derbytools-10.8.2.2.jar
-rw-r--r-- 1 henry henry 6412045 2014-03-06 21:17 ./dependency/eclipselink-2.2.1.jar
-rw-r--r-- 1 henry henry  126856 2014-03-06 21:17 ./dependency/javax.persistence-2.0.3.jar

6. Run As Java Application

henry@brimley:~/Test/jpatest/test1$ cd target/classes
henry@brimley:~/Test/jpatest/test1/target/classes$ java -cp '../dependency/*' henry416.jpa.JpaTest
num of employess:2
next employee: Employee [id=3, name=Captain Nemo, department=java]
next employee: Employee [id=2, name=Jakab Gipsz, department=java]
.. done

7. Summary

By using maven, it’s pretty easy to create a project structure for a JPA application (Kudos to you Lajos Papp). By replacing those POJO entity classes with your own classes, modifying persistence.xml to your local database and pom.xml to the latest maven repository, you can code a real world java application in JPA. I hope this will make JPA programming more interesting.

Undocumented SQL Server 2012 Express LocalDB

As a developer of Microsoft Visual Studio, SQL Server 2012 Express LocalDB probably has gotten onto your machine without your notice. I will document some of my exploration on LocalDB in this post.

Installation and Location

There are three ways to get LocalDB onto your machines:

  1. Install together when installing Microsoft Visual Studio 2013 (this is my case);
  2. Install by using SqlLocalDB.msi found in SQL Server 2012 Express
  3. Install by downloading from Microsoft Download Centre directly (here).

The installation location is default to C:\Program Files\Microsoft SQL Server\110\LocalDB\Binn where sqlserv.exe is the main application.

The tools (utilities) to operate the LocalDB are SqlLocalDB, SQLCMD and bcp which are located at C:\Program Files\Microsoft SQL Server\110\Tools\Binn. Make sure to include it into your PATH.

SqlLocalDB

This is the utility to administrate the localdb instances.

  • to get help: sqllocaldb -?
  • to print the version: sqllocaldb versions
  • to create an instance: sqllocaldb create “YourInstanceName”
  • to delete an instance: sqllocaldb delete “YourInstanceName”
  • to start an instance: sqllocaldb start “YourInstanceName”
  • to stop an instance: sqllocaldb stop “YourInstanceName”
  • to share an instance: sqllocaldb share “YourInstanceName”
  • to unshared an instance: sqllocadbl unshare “YourInstanceName”
  • to list all your instances: sqllocaldb info
  • to list the status of an instance: sqllocaldb info “YourInstanceName”
  • to set the trace on and off: sqllocaldb trace on|off

If you’ve used VS 2013 to connect to LocalDB, VS 2013 would have created an instance for you (in my case is v11.0).

Even your instance is stopped, it will be auto-started when you try to connect to it first time either via VS 2013 or SQLCMD.

SQLCMD, BCP, process ‘sqlservr’

Both SQLCMD and BCP are well documented. The only difference between LocalDB and SQL server is that we need to put a bracket ‘()’ to indicate it is a LocalDB instead of hostname for the named instance like:

sqlcmd -S ‘(LocalDB)\v11.0′

This is also applied to SSMS and VS 2013 connections. There is only one process “sqlservr” related to LocalDB. It is very lightweighted by using about 12MB RAM on my machine.

Some Examples

The following is executed in powershell:

Windows PowerShell
Copyright (C) 2013 Microsoft Corporation. All rights reserved.

PS C:\Users\henry> sqllocaldb info
Projects
v11.0
PS C:\Users\henry> sqllocaldb info "v11.0"
Name:               v11.0
Version:            11.0.3000.0
Shared name:
Owner:              PolarBear\henry
Auto-create:        Yes
State:              Stopped
Last start time:    12/31/2013 2:37:39 PM
Instance pipe name:
PS C:\Users\henry> sqllocaldb start "v11.0"
LocalDB instance "v11.0" started.
PS C:\Users\henry>  ps | where-object {$_.ProcessName -match 'sqlservr'}

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    492      20    67780      17140   311     3.83   2248 sqlservr


PS C:\Users\henry> sqllocaldb stop "v11.0"
LocalDB instance "v11.0" stopped.
PS C:\Users\henry> sqlcmd -S "(LocalDB)\v11.0"
1> use test
2> go
Changed database context to 'test'.
1> select count(*) from HR.Employees
2> go

-----------
          9

(1 rows affected)
1> shutdown
2> go
Server shut down by request from login PolarBear\henry.
1> exit
PS C:\Users\henry>

Sharing or Not

From A TechNet Article
When sharing a SqlLocalDB instance with a non-owner, you must re-start the instance for the other users to be able to see the instance you have shared. A non-owner cannot start an instance, so if you are going to share an instance with other users who can access your machine, you also need to be sure it has been started. When you create an instance you can do this as follows:

sqllocaldb create “MyInstance”
sqllocaldb share “MyInstance” “OurInstance”
sqllocaldb start “MyInstance”

You should add users explicitly when connected to the instance as the owner, e.g.

CREATE LOGIN [Domain\User] FROM WINDOWS;
GRANT CONNECT TO [Domain\User];
— other permissions…

In general, though, the purpose of SqlLocalDB is to serve as a sandbox for an individual developer on a machine, not to serve as a development environment for multiple users. Each user should be able to create, start, administer and use his/her own LocalDB instances.

Consume Web API in a .NET C# client

Recently I have written a console client in C# to consume those web services developed in my previous post by using APS.NET Web API 2 and Microsoft Entity Framework 6.

I started with a new Console Application (called WebApiClient) in C# in Visual Studio 2013, and then installed the Microsoft ASP.NET Web API Class Libraries using NuGet. Lastly, I added Employee.cs (model class) which was used by web services as my data structure.

The following is a web client program in C# (Program.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace WebApiClient
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            string baseUrl = "http://localhost:55142";
            client.BaseAddress = new Uri(baseUrl);
            
            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            //New Employee Record URL
            int anEmpId = -1;
            string serviceUrl;


            // 1. Post a new employee
            serviceUrl="api/employee";
            Console.WriteLine("1. Add an employee by sending POST {0}/{1}  \r\n", baseUrl, serviceUrl);
            Console.WriteLine("The following new employee is added  \r\n");
            var anEmployee = new Employee() { 
                lastname = "Smith",
                firstname = "Adam",
                title = "Economist",
                titleofcourtesy = "Dr.",
                birthdate = Convert.ToDateTime("1958-12-05 "),
                hiredate = Convert.ToDateTime("1990-01-01"),
                address = "188 Bay Street",
                city = "London",
                region = "",
                postalcode = "A1B 2Z3",
                country = "UK",
                phone = "(71) 234-8228",
                mgrid = 1};
            

            HttpResponseMessage response = client.PostAsJsonAsync(serviceUrl, anEmployee).Result;
            if  (response.IsSuccessStatusCode)
            {

                // display the new employee
                Console.WriteLine("firstname={0}", anEmployee.firstname);
                Console.WriteLine("lastname={0}", anEmployee.lastname);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            Console.WriteLine("\r\nCheck your database table. Press any key to continue...\r\n");
            Console.ReadKey();


            // 2. Get all employees.
            serviceUrl="api/employee";
            Console.WriteLine("2. Get All Employee by sending GET {0}/{1} \r\n", baseUrl, serviceUrl);

            response = client.GetAsync(serviceUrl).Result;        // Blocking call!
            if  (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var employees = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result;
                foreach (var e in employees)
                    {
                         
                        if (e.firstname.Equals("Adam") & e.lastname.Equals("Smith"))
                        { 
                            anEmpId = e.empid;
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("{0};\t{1};\t{2};\t{3}", e.empid, e.firstname, e.lastname, e.title);
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("\r\nThe new employee is with empid={0}\r\n", anEmpId);
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }
                        else
                        {
                            Console.WriteLine("{0};\t{1};\t{2};\t{3}", e.empid, e.firstname, e.lastname, e.title);
                        }
                    }
            }
            else
            {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            Console.WriteLine("\r\nPress any key to continue...\r\n");
            Console.ReadKey();

            // 3. Get an employee by empid
            if (anEmpId>0)
            {
                serviceUrl = "api/employee/" + anEmpId.ToString();

            }
            else
            {
                serviceUrl = "api/employee/1";
                anEmpId = 1;
            }

            Console.WriteLine("3. Get the employee with empid={0} by sending GET {1}/{2} \r\n", anEmpId, baseUrl, serviceUrl);

            response = client.GetAsync(serviceUrl).Result;        // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var a_employee = response.Content.ReadAsAsync<Employee>().Result;

                Console.WriteLine("emid={0}", a_employee.empid);
                Console.WriteLine("FirstName={0}", a_employee.firstname);
                Console.WriteLine("LastName={0}", a_employee.lastname);
                Console.WriteLine("Title={0}", a_employee.title);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            Console.WriteLine("\r\nPress any key to continue...\r\n");
            Console.ReadKey();

            // 4. Update an employee by empid
            Console.WriteLine("4. Update an employee with empid = {0} by sending PUT {1}/{2} \r\n", anEmpId, baseUrl, serviceUrl);

            response = client.GetAsync(serviceUrl).Result;        // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Retrieve the record first
                var a_employee = response.Content.ReadAsAsync<Employee>().Result;
                Console.WriteLine("The record is retrieved before update: \r\n");
                Console.WriteLine("emid={0}", a_employee.empid);
                Console.WriteLine("FirstName={0}", a_employee.firstname);
                Console.WriteLine("LastName={0}", a_employee.lastname);
                Console.WriteLine("Title={0}", a_employee.title);

                // Update the tile field of the record
                a_employee.title = "Senior Economist";

                response = client.PutAsJsonAsync(serviceUrl, a_employee).Result;

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("\r\nThe record with empid={0} was updated with the following: \r\n", anEmpId);
                    Console.ForegroundColor = ConsoleColor.Yellow; 
                    Console.WriteLine("Title={0}", a_employee.title);
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
            Console.WriteLine("\r\nCheck your database table. Press any key to continue...\r\n");
            Console.ReadKey();

            // 5. delete an employee added in step 1
            Console.WriteLine("4. Delete an employee with empid = {0} by sending DELETE {1}/{2} \r\n", anEmpId, baseUrl, serviceUrl);

            response = client.DeleteAsync(serviceUrl).Result;
             if (response.IsSuccessStatusCode)
             {
                 Console.ForegroundColor = ConsoleColor.Yellow;
                 Console.WriteLine("The record with empid={0} was deleted.", anEmpId);
                 Console.ForegroundColor = ConsoleColor.Gray;
             }
             else
             {
                 Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
             }
             Console.WriteLine("\r\nCheck your database table.\r\n");
        }
    }
}

Virtualbox: How to sync time VM client in Windows

I am running a few Virtual Machines on my PC by using Oracle Virtualbox. There is always a need to sync the time on VM clients. The following commands are used in my Windows 8 VM client to sync to the time server in Canada by ‘run as Administrator':

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Windows\system32>net stop w32time
The Windows Time service is stopping.
The Windows Time service was stopped successfully.

C:\Windows\system32>w32tm /debug /disable

C:\Windows\system32>w32tm /unregister
W32Time successfully unregistered.

C:\Windows\system32>w32tm /register
W32Time successfully registered.

C:\Windows\system32>net start w32time
The Windows Time service is starting.
The Windows Time service was started successfully.

C:\Windows\system32>w32tm /config /manualpeerlist:time.nrc.ca,0x8, /syncfromflags:manual /update
The command completed successfully.

C:\Windows\system32>w32tm /resync
Sending resync command to local computer
The command completed successfully.
Follow

Get every new post delivered to your Inbox.