Sub topic 13
Creating junction records in Apex
This chapter shows how to create junction records from Apex code. You should already know how a junction object works, with two master-detail fields, and how to read basic Apex and SOQL. The examples use the model from earlier chapters. Enrollment__c is the junction object. It has a master-detail field Course__c to Course__c and another, Student__c, to Student__c.
What the junction record needs
A junction record is a child of two parents. Because both fields are master-detail, both are required. Apex enforces this at insert time, not when the object is defined.
- Both parent records must already exist and have an Id.
- Both lookup fields on the junction record must be set to those Ids.
- The junction record has no owner. Setting
OwnerIdon it fails, because master-detail children inherit ownership from the primary master. - The running user must be allowed to create child records under both masters. By default this means Read/Write access to the master records. If the field metadata sets
writeRequiresMasterReadtotrue, Read access is enough.
The basic pattern is two inserts for the parents, then one for the junction record.
Course__c course = new Course__c(Name = 'Apex Basics');
Student__c student = new Student__c(Name = 'Ada Lovelace');
insert course;
insert student;
insert new Enrollment__c(Course__c = course.Id, Student__c = student.Id);Apex fills in course.Id and student.Id after each insert runs. If you build the Enrollment__c before inserting the parents, both fields are null and the insert fails with REQUIRED_FIELD_MISSING.
Creating junction records in bulk
Triggers, batch jobs, and imports rarely create one record at a time. Apex limits a transaction to 150 DML statements, so build a list and insert it once.
This service method enrolls many students in one course. It queries for existing junction records first, because Salesforce does not stop you from creating the same pair twice.
public with sharing class EnrollmentService {
public static List<Enrollment__c> enroll(Id courseId, Set<Id> studentIds) {
Set<Id> alreadyEnrolled = new Set<Id>();
for (Enrollment__c existing : [
SELECT Student__c
FROM Enrollment__c
WHERE Course__c = :courseId
AND Student__c IN :studentIds
]) {
alreadyEnrolled.add(existing.Student__c);
}
List<Enrollment__c> toInsert = new List<Enrollment__c>();
for (Id studentId : studentIds) {
if (!alreadyEnrolled.contains(studentId)) {
toInsert.add(new Enrollment__c(
Course__c = courseId,
Student__c = studentId
));
}
}
insert toInsert;
return toInsert;
}
}Three details matter here:
- The method does one query and one DML statement, however many students it receives.
- Inserting an empty list is legal and does nothing, so you don't need a size check.
- The class uses
with sharing, so the query and the insert respect the running user's access.
Handling many courses at once
If the input is a list of (course, student) pairs, the single-course query above does not work. Querying Course__c IN :courseIds AND Student__c IN :studentIds also returns pairs you did not ask about, such as course A with student 2 when you only asked about course A with student 1. Build a composite key instead.
public with sharing class EnrollmentPairs {
public static String key(Id courseId, Id studentId) {
return String.valueOf(courseId) + '|' + String.valueOf(studentId);
}
public static void enrollPairs(List<Enrollment__c> requested) {
Set<Id> courseIds = new Set<Id>();
Set<Id> studentIds = new Set<Id>();
for (Enrollment__c req : requested) {
courseIds.add(req.Course__c);
studentIds.add(req.Student__c);
}
Set<String> existingKeys = new Set<String>();
for (Enrollment__c e : [
SELECT Course__c, Student__c
FROM Enrollment__c
WHERE Course__c IN :courseIds
AND Student__c IN :studentIds
]) {
existingKeys.add(key(e.Course__c, e.Student__c));
}
List<Enrollment__c> toInsert = new List<Enrollment__c>();
for (Enrollment__c req : requested) {
String k = key(req.Course__c, req.Student__c);
if (!existingKeys.contains(k)) {
existingKeys.add(k);
toInsert.add(req);
}
}
insert toInsert;
}
}The query can still over-fetch, but the key check discards pairs that were not requested. Adding each new key to existingKeys also removes duplicates inside the input list.
Handling failures
A plain insert is all-or-nothing. If one junction record in a list fails, the whole statement throws a DmlException and nothing is saved. When you want the valid records saved and a report on the rest, use Database.insert with allOrNone set to false.
List<Enrollment__c> candidates = new List<Enrollment__c>();
// ... fill candidates ...
List<Database.SaveResult> results = Database.insert(candidates, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug(
'Row ' + i + ' failed: ' + err.getStatusCode()
+ ' - ' + err.getMessage()
);
}
}
}The results list is in the same order as the input list, so index i identifies the failed record.
Common failures when creating junction records:
| Status code | Typical cause | Fix |
|---|---|---|
| `REQUIRED_FIELD_MISSING` | One of the two master-detail fields is null, often because a parent was not inserted yet | Insert parents first and copy their Ids |
| `ENTITY_IS_DELETED` | A parent Id points to a deleted record | Re-query the parents, or skip deleted ones |
| `INSUFFICIENT_ACCESS_OR_READONLY` | The user cannot create children under that master | Check sharing on the parent and the master-detail sharing setting |
| `INVALID_CROSS_REFERENCE_KEY` | The Id is not a valid Id of the parent's object type | Check that the Ids are in the right fields |
| `FIELD_INTEGRITY_EXCEPTION` | A lookup filter or validation rule rejected the value | Review filters and validation rules on the junction object |
Parents are fixed after creation
The metadata example in this tutorial sets reparentableMasterDetail to false. With that setting, you cannot change a junction record's Course__c or Student__c once it is saved. An update that does so fails. To move a student to a different course, delete the old Enrollment__c record and insert a new one. If you set the field to true, updates are allowed, but then sharing and roll-up values on both the old and new parent are recalculated.
Deleting and cascading
You do not need to delete junction records before you delete a parent. Deleting a Course__c also deletes its Enrollment__c records, because master-detail relationships cascade. The students stay. Undeleting the course restores its enrollments.
If you delete a parent in Apex, you can count what will go with it first. Child counts are useful in confirmation messages.
Reading the result back
After you insert junction records, a subquery through the child relationship name shows the students of a course. The relationship name is Enrollments__r, as defined by the master-detail field's relationship name.
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'In Apex, the same query returns Course__c records whose Enrollments__r list you can loop over.
List<Course__c> courses = [
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'
];
for (Course__c c : courses) {
for (Enrollment__c e : c.Enrollments__r) {
System.debug(c.Name + ': ' + e.Student__r.Name);
}
}If a course has no enrollments, c.Enrollments__r is an empty list in Apex, so the loop is safe.
Counting children when you cannot roll up
Master-detail relationships support roll-up summary fields, so Course__c can hold a count of enrollments without any code. Lookup relationships cannot. If the junction model used lookups, or you need a count on a parent that has only a lookup child, an aggregate query is one way to get it.
Set<Id> accountIds = new Set<Id>{ '001000000000001AAA' };
List<AggregateResult> totals = [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
];The Id here is a placeholder. Replace it with a real account Id before you run the code. Read each count with (Integer) totals[0].get('total').
Testing junction code
A test must create both parents, then the junction record, and then assert on what was saved. Test methods cannot see your org's data by default, so the test makes its own.
@IsTest
private class EnrollmentServiceTest {
@IsTest
static void enrollSkipsExistingPairs() {
Course__c course = new Course__c(Name = 'Apex Basics');
insert course;
List<Student__c> students = new List<Student__c>{
new Student__c(Name = 'Ada Lovelace'),
new Student__c(Name = 'Grace Hopper')
};
insert students;
insert new Enrollment__c(
Course__c = course.Id,
Student__c = students[0].Id
);
Test.startTest();
List<Enrollment__c> created = EnrollmentService.enroll(
course.Id,
new Set<Id>{ students[0].Id, students[1].Id }
);
Test.stopTest();
System.assertEquals(1, created.size(), 'Only the new pair is inserted');
System.assertEquals(2, [
SELECT COUNT() FROM Enrollment__c WHERE Course__c = :course.Id
]);
}
}Also test the case with more than 200 junction records. Apex splits large DML into chunks of 200 records, and a test with 201 or more records confirms that your code does not hit a limit or fire a trigger in an unexpected way.
Summary of rules
- Insert both parents before the junction record.
- Set both master-detail fields on the junction record. Do not set
OwnerId. - Build a list and insert once. Check for duplicates yourself.
- Use
Database.insert(records, false)when you want partial success and per-record errors. - Delete and re-create a junction record to change a parent when the field is not reparentable.
- Deleting a parent deletes its junction records.
Exercise
A trigger on Student__c builds an Enrollment__c for each new student and inserts it in the same after insert handler. The Enrollment__c records set Course__c but the insert fails with REQUIRED_FIELD_MISSING. What is missing, and why does the order of operations not explain it here?
Show answer
The Student__c field is missing. Both master-detail fields are required. In an after-insert trigger the new students already have Ids, so the order is fine. The code must set Student__c = student.Id for each record in Trigger.new.
Exercise
Your batch job inserts 5,000 Enrollment__c records with Database.insert(records, false). After it runs, you find that 40 records were not saved and no exception was thrown. How do you find out why, and how do you tell which input record each failure belongs to?
Show answer
Inspect the List<Database.SaveResult> the call returns. It is in the same order as the input list, so index i in the results matches records[i]. For each result where isSuccess() is false, read getErrors() and log the status code and message. Without checking the results, partial-success inserts fail silently.